Bug Report
🔎 Search Terms
object literal definition type narrowing type guard
Possibly related: #16896 (especially this comment).
🕗 Version & Regression Information
This is the behavior in every version I tried, and I reviewed the FAQ for entries about 'object' and 'literal'
⏯ Playground Link
Playground link with relevant code
💻 Code
interface Test
{
a?: number;
}
let x: Test = { a: 23 };
// Error: Type 'number | undefined' is not assignable to type 'number'. (2322)
const val: number = x.a;
🙁 Actual behavior
The compiler does not recognize that the type of property a should be narrowed to number due to the literal definition. This is always a surprise.
🙂 Expected behavior
I expect the type to be narrowed such that the property a is treated as "narrowed to number" until otherwise modified in the scope that follows the assignment.
This feels entirely natural as it's how most other assignments work. This comment puts it nicely:
Initializations are just treated as assignments. So this is basically const value: number | null; value = 123;, and no one would expect value to be possibly null right after assigning a number to it.
In this case, I do not expect x.a to be missing right after assigning to it an object literal with a defined.
Bug Report
🔎 Search Terms
object literal definition type narrowing type guard
Possibly related: #16896 (especially this comment).
🕗 Version & Regression Information
This is the behavior in every version I tried, and I reviewed the FAQ for entries about 'object' and 'literal'
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
The compiler does not recognize that the type of property
ashould be narrowed tonumberdue to the literal definition. This is always a surprise.🙂 Expected behavior
I expect the type to be narrowed such that the property
ais treated as "narrowed tonumber" until otherwise modified in the scope that follows the assignment.This feels entirely natural as it's how most other assignments work. This comment puts it nicely:
In this case, I do not expect
x.ato be missing right after assigning to it an object literal withadefined.