typescript - 将 switch 语句案例移动到自己的函数时出现 TypeScript 错误?
问题描述
我将 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 错误:
“操作”类型上不存在属性“索引”。类型 '{ type: "do-something"; 上不存在属性 'index' 宽度:数字;isLandscape:布尔值;}'.ts(2339)
我可以看到 TypeScript 不知道由于 switch 语句,action
对象将具有和index
属性。有没有办法让它意识到这一点?
解决方案
函数不适doSomething
用于所有动作,但对于具有index
属性的动作,我会拆分一些打字,以便能够更清楚地键入需求:
type A = {
type: "do-other-thing";
name: string;
};
type B = {
type: "do-something";
index: number;
};
type Action = A | B
function doSomething(state: state, action: B): state {
if (action.index === 0) return state;
// more logic
}
现在仅适用于您的类型doSomething
的变体。B
Action
推荐阅读
- c# - c#删除字符串的所有包装div
- python - ValueError:尺寸必须相等,但对于输入形状为 [?,13]、[?,13,3076] 的“loss/dense_1_loss/mul”(操作:“Mul”),尺寸必须是 13 和 3076
- c++ - 成员初始化查询
- c# - 为什么 C# 类库中的静态变量在从 VBA 实例化的对象中仍然存在?
- jquery - Ajax 调用成功后重新加载当前页面
- clickhouse - Cannot install a new clickhouse-server. Installation fails with Poco::Exception. Code: 1000
- karate - 处理具有日期类型字段的数据库记录的最佳方法是什么?
- python - 吸气剂还是二传手?
- python - 通过ORM关系获取子表
- matlab - 使用带有选项的 parfor 来并行化代码