איך לאכוף סוג של פונקציה מיוצאת ב-TypeScript?
היה לי את זה:
export const counterReducer: ActionReducer<number> = (state = 0, action: Action) => {
const at = CounterActions;
switch (action.type) {
case at.incrementId:
return state + 1;
case at.decrementId:
return state - 1;
case at.resetId:
return 0;
default:
return state;
}
};
לצערי הייתי צריך לכתוב את זה מחדש בצורת export function (בלעדיה AoT לא יעבוד):
export function counterReducer(state = 0, action: Action): number {
const at = CounterActions;
switch (action.type) {
case at.incrementId:
return state + 1;
case at.decrementId:
return state - 1;
case at.resetId:
return 0;
default:
return state;
}
}
כפי שאתה יכול לראות, איבדתי את סוג הפונקציה המלאה (ActionReducer<number>), וזה לא מקובל עלי.
אז השאלה היא:
איך ניתן להקנות טיפוס ל-export function? איך ניתן להגדיר את הטיפוס בנקודת ההגדרה?
תשובה #1
אתה יכול לייצא פונקציה מוקלדת כך:
export const counterReducer = (state = 0, action: Action) => ({
..
} as ActionReducer<number>);
