Skip to content

Refine unions in contextual typing #16457

@RyanCavanaugh

Description

@RyanCavanaugh

Source issue #16450 and others (TODO: find them)

This code should work, but doesn't:

interface X {
    type: 'x';
    value: string;
}

interface Y {
    type: 'y';
    value: 'none' | 'done';
}

function foo(bar: X | Y) { }

foo({
    type: 'y',
    value: 'done',
});

Similar example:

interface X {
    type1: 'x';
    value: string;
}

interface Y {
    type2: 'y';
    value: 'none' | 'done';
}

function foo(bar: X | Y) { }

foo({
    type2: 'y',
    value: 'done',
});

We can, in principle, make this work by discarding X from the union.

In the first example, this can be done (somehow) by using the discriminating union from the object literal.

In the second example, this can be done by noting that we have a fresh object literal type (meaning there are known to be no additional properties) and a missing type1 property.

Metadata

Metadata

Assignees

Labels

SuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions