interface Test {
a: string;
b: number;
c: number;
}
const test = {
a: 'a',
b: 1,
d: []
};
delete test.d;
const test2:Test = { ...test, c:1 };
=> Type '{ a: string; b: number; c: number; d: never[]; }' is not assignable to type 'Test'.
=> Object literal may only specify known properties, and 'd' does not exist in type 'Test'.
Run Code Online (Sandbox Code Playgroud)
我通过删除运算符删除了d属性,但出现了类似的错误。
针对这种情况有办法吗?
变量的类型是在赋值时推断的,我不认为 Typescript 使用删除运算符执行任何流程控制魔法。您可以使用展开运算符来摆脱d:
interface Test {
a: string;
b: number;
c: number;
}
const test = {
a: 'a',
b: 1,
d: []
};
let { d, ...test3} = test
const test2:Test = { ...test3, c:1 };
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5340 次 |
| 最近记录: |