Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript does not infer about delete operator and spread operator?

Tags:

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

I deleted d property by delete operator, but I got a error like that.

Is there a way for the situation?

like image 262
left click Avatar asked Nov 02 '25 02:11

left click


1 Answers

The type of the variable is infered on assignment, and I don't think Typescript does any flow control magic with the delete operator. You could the spread operator to get rid of 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 };
like image 148
Titian Cernicova-Dragomir Avatar answered Nov 04 '25 04:11

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!