【发布时间】:2019-11-14 15:56:24
【问题描述】:
我创建了两个代码示例。它们之间的唯一区别是我传递给 switch 运算符的表达式。
在第一种情况下,我使用对象属性。而且效果很好。
在第二种情况下,我创建了一个 type 变量。并且 Typescript 会抛出错误消息:
“操作”类型上不存在属性“名称”。
类型 '{ type: "reset"; 上不存在属性 'name'; }'。
为什么会这样?
对象属性action.type和变量type属于同一类型'reset' | 'update' 。
interface State {
name: string;
cars: any[];
}
type Action = { type: 'reset' } | { type: 'update', name: string };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'update':
return { ...state, name: action.name };
case 'reset':
return {...state, cars: [] };
default:
throw new Error();
}
}
interface State {
name: string;
cars: any[];
}
type Action = { type: 'reset' } | { type: 'update', name: string };
function reducer(state: State, action: Action): State {
/**
* Create a 'type' variable
*/
const { type } = action;
switch (type) {
case 'update':
return { ...state, name: action.name };
/**
* Typescript will throw an error message
* Property 'name' does not exist on type 'Action'.
* Property 'name' does not exist on type '{ type: "reset"; }'.
*/
case 'reset':
return {...state, cars: [] };
default:
throw new Error();
}
}
【问题讨论】:
-
type Action = { type: 'reset' } | { 类型:'更新',名称:字符串 };您必须在此处为 name 属性设置一个值,而不是 name: string.
标签: typescript redux