我正在将 TypeScript 与 Redux 结合使用。此代码运行良好:
export type action =
| {
type: "do-other-thing";
name: string;
}
| {
type: "do-something";
index: number;
};
function reducer(state: state = initState, action: action): state {
switch (action.type) {
case "do-something":
if (action.index === 0) return state;
// More logic
case "do-other-thing":
// More logic
default:
return state;
}
但是我想将 switch 语句中的返回情况移至它们自己的函数中:
function doSomething(state: state, action : action): state {
if (action.index === 0) return state;
// more logic
}
function reducer(state: state = initState, action: action): state {
switch (action.type) {
case "do-something":
return doSomething(state, action);
case "do-other-thing":
// More logic
default:
return state;
}
现在 doSomething
函数出现 TypeScript 错误:
Property 'index' does not exist on type 'action'. Property 'index' does not exist on type '{ type: "do-something"; width: number; isLandscape: boolean; }'.ts(2339)
我可以看到 TypeScript 不知道由于 switch 语句,action
对象将具有 index
属性。有没有办法让它意识到这一点?
最佳答案
因为您在 doSomething
函数上将参数定义为 action
,所以任何人都可以在其他地方传递任何 action
。您很可能希望将其实际定义为更受限制的类型,如下所示:
type DoOtherThingAction = { type: "do-other-thing"; name: string; };
type DoSomeThingAction = { type: "do-something"; index: number; };
export type action =
| DoOtherThingAction
| DoSomeThingAction;
然后:
function doSomething(state: state, action : DoSomeThingAction): state {
if (action.index === 0) return state;
// more logic
}
关于当我将 switch 语句案例移动到自己的函数时出现 TypeScript 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60602811/