4
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?

2
  • 1
    I think it is case, when type casting with const test2:Test = { ...test, c:1 } as Test; is acceptably. Commented Mar 31, 2018 at 19:52
  • @Pavel Thanks for your idea! Commented Apr 1, 2018 at 6:04

2 Answers 2

6

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 };
Sign up to request clarification or add additional context in comments.

2 Comments

It's a good idea, except that additional variable are used. Thank you! :)
@leftclick not ideal i know, there may be other solutions ... i can think of one with an extra function, or one that usses a type guard .. but none are perfect
-1

If you are using a tsconfig.json file, consider adding:

{
  "compilerOptions": {
    ...
     "strictNullChecks": false, 
    }
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.