Skip to content

Object Literal Assignment Does Not Participate in Type Narrowing #46489

@ericdrobinson

Description

@ericdrobinson

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions