我想從 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.
uj5u.com熱心網友回復:
您可以使用條件型別將元組型別傳播到其余引數,根據是否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;
}
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414473.html
標籤:
