以下是我的类型:
const classRoom: Classroom<User> = ...
现在说我以某种方式创建了一个教室实例:
someAction
调用// No warning, and this is correct
classRoom.someAction((state) => {
return {
...state
};
});
// No warning, and this is correct
classRoom.someAction((state) => {
return {
...state,
age: 123
};
});
// Warning, but this is also correct warning
classRoom.someAction((state) => {
return {
...state,
age: 'sdf'
};
});
// Now this fails
// The property `foo` is incorrect; but there is no warning
classRoom.someAction((state) => {
return {
...state,
foo: 123
};
});
// But then this fixes it, but it is redundant
classRoom.someAction((state): User => {
return {
...state,
foo: 123
};
});
现在的行为不符合我的预期:
cygpath -aw
我做错了什么?
答案 0 :(得分:0)
关于额外属性的警告仅触发对象文字。
// warning, object literals may only specify known properties
const x: {y: number} = {y: 42, z: 30};
具有对象传播的对象没有此警告。话虽如此,从打字的角度来看,额外的属性并不重要,所有必需的属性仍然存在。
如果您对此有强烈的感受,请someAction
回调不知道state
并且不要将其用于与您提供的属性合并,而是在不同的图层上进行。