TypeScript 无法推断删除运算符和扩展运算符?

lef*_*ick 4 typescript

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属性,但出现了类似的错误。

针对这种情况有办法吗?

Tit*_*mir 6

变量的类型是在赋值时推断的,我不认为 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)