gpt4 book ai didi

typescript 不推断删除运算符和展开运算符?

转载 作者:搜寻专家 更新时间:2023-10-30 21:10:14 26 4
gpt4 key购买 nike

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'.

我用 delete 操作符删除了 d 属性,但我得到了这样的错误。

这种情况有办法吗?感谢阅读!

最佳答案

变量的类型是在赋值时推断出来的,我不认为 Typescript 对 delete 运算符有任何流控制魔法。您可以使用传播运算符来摆脱 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 };

关于 typescript 不推断删除运算符和展开运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49590146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com