Skip to content

Unable to cast to generic discriminated union #39075

@helmutschneider

Description

@helmutschneider

TypeScript Version: 3.9.5

Search Terms: discriminated union, generics, cast

Code

enum Color {
    Red,
    Blue,
}
type Attributes = {
    [Color.Red]: {
        a: 'red'
    }
    [Color.Blue]: {
        b: 'blue'
    }
}
type ColorWithAttributes<T extends Color> = { color: T } & Attributes[T]
type ColorLike =
    | ColorWithAttributes<Color.Red>
    | ColorWithAttributes<Color.Blue>

function make<T extends Color>(color: T, args: Attributes[T]): ColorLike {
    const x: ColorWithAttributes<T> = {
        color,
        ...args,
    }
    
    return x as ColorLike // <-- fails with TS2352
}

Expected behavior:
Cast should not fail. Works correctly on 3.8.3.

Actual behavior:
Cast fails with error TS2352.

Playground Link:
Link

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: check: Type InferenceRelated to type inference performed during signature resolution or `infer` type resolution

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions