如何在函数 props 中声明一个可选的泛型类型?
How to declare an optional generic type in an function props?
我想从 redux-toolkit 创建类似于 createAction 的东西。
我需要将有效负载类型传递给 createAction,但我不明白如果传递了可选的 属性 则如何强制执行。
这是我的实现。
type ActionFormat<P = undefined> = {type: string} & (P extends undefined ? {} : {payload: P})
export function createAction<P = undefined>(type: string): (payload?: P) => ActionFormat {
const actionCreator = (payload?: P) => ({ type, payload: payload });
return actionCreator;
}
创建动作
const startFetch = createAction('START_FETCH');
const successFetch = createAction<number>('SUCCESS_FETCH')
运行 操作
startFetch(); //there are no errors. No payload required
startFetch('test'); //must be an error Payload has been submitted
successFetch(); //must be an error Payload was not submitted
successFetch(123); // there are no errors.
您可以使用条件类型将元组类型扩展到剩余参数,根据 P
是否扩展 undefined
(即 undeinfed
是否需要参数)或包含未定义的联合)
export function createAction<P = undefined>(type: string): (...payload:
P extends undefined
? [payload?: P] // P === undefined, no parameters required, but pay be passed in.
: [payload: P] //P does not contain undefined parameter is required
) => ActionFormat {
const actionCreator = (payload?: P) => ({ type, payload: payload });
return actionCreator;
}
我想从 redux-toolkit 创建类似于 createAction 的东西。 我需要将有效负载类型传递给 createAction,但我不明白如果传递了可选的 属性 则如何强制执行。
这是我的实现。
type ActionFormat<P = undefined> = {type: string} & (P extends undefined ? {} : {payload: P})
export function createAction<P = undefined>(type: string): (payload?: P) => ActionFormat {
const actionCreator = (payload?: P) => ({ type, payload: payload });
return actionCreator;
}
创建动作
const startFetch = createAction('START_FETCH');
const successFetch = createAction<number>('SUCCESS_FETCH')
运行 操作
startFetch(); //there are no errors. No payload required
startFetch('test'); //must be an error Payload has been submitted
successFetch(); //must be an error Payload was not submitted
successFetch(123); // there are no errors.
您可以使用条件类型将元组类型扩展到剩余参数,根据 P
是否扩展 undefined
(即 undeinfed
是否需要参数)或包含未定义的联合)
export function createAction<P = undefined>(type: string): (...payload:
P extends undefined
? [payload?: P] // P === undefined, no parameters required, but pay be passed in.
: [payload: P] //P does not contain undefined parameter is required
) => ActionFormat {
const actionCreator = (payload?: P) => ({ type, payload: payload });
return actionCreator;
}