Sep 1, 2018 · 1 min read
If you want to work around TypeScript’s requirement to explicitly declare typeof SET_AGE, you can use one function per generic argument:
type Action<T extends string = string, P = void> = P extends void
? Readonly<{ type: T }>
: Readonly<{ type: T; payload: P }>function action<T extends string>(type: T) {
function actionPayload(): () => Action<T>
function actionPayload<P>(): (payload: P) => Action<T, P>
function actionPayload<P>() {
return (payload?: P) => ({ type, payload })
}
return actionPayload
}const SET_AGE = "[user] set_age"
const setAge = action(SET_AGE)<number>()
type SetAgeAction = ReturnType<typeof setAge>
alert(JSON.stringify(setAge(20)));const SAVE = "[user] save"
const save = action(SAVE)()
type SaveAction = ReturnType<typeof save>
alert(JSON.stringify(save()));
(This is the approach suggested as “workaround” in Microsoft/TypeScript#10571.)
What do you think? Is this enough of an improvement to change your preferred pattern?
