microsoft/TypeScript

Spread of partial interface can lead to runtime error when explicitly setting a prop to undefined.

Ranguna opened this issue · 2 comments

TypeScript Version: 3.9.1, v4.0.0-dev.20200516

Search Terms: interface partial spread runtime error, interface partial spread

Code

interface B {
    b: number
}

interface A {
    a: B;
}

const fn = (arg: Partial<A>): A => ({a:{b:2}, ...arg});

let aRes = fn({a:undefined});
console.log(aRes.a.b);

Expected behavior:
I expected the program to fail to compile because any prop in Partial<A> can be explicitly set to undefined, which overrides it's corresponding value when spreaded over another object of type A. This causes the return value of fn to not be described by A, but instead by an interface similar to A where all props can be undefined as well.

Actual behavior:
Got the following runtime error: TypeError: "aRes.a is undefined".

Playground Link: https://www.typescriptlang.org/play?ts=4.0.0-dev.20200516#code/JYOwLgpgTgZghgYwgAgELIN4Chm+QIwC5kQBXAW32iwF8stRJZEUBBTHPOY1AblvoIA9iADOYZDBDIAvMgAUcKAHNiABSVhgcADYAeVgD4AlMXYzDCjNwxEATDQA0yAHRulymsf5YdECXAAShCispIg8taEpCAAJhAwoBCxXvzCYkJ+LjpCyorBoi5wLvjeQA

Related Issues: (The other way round, but not really it) #16509, (duplicates) #13195.

Essentially a duplicate of #13195.

Oops, indeed!
Thank you, and I'm sorry for causing a duplicate.
Closing in favor of #13195.