Skip to content

Erroneous error when assigning to string literal union type #11714

Closed
@pelotom

Description

@pelotom

TypeScript Version: 2.0.3 / nightly (2.1.0-dev.201xxxxx)

Code

type T = {
  xOrY: 'x' | 'y'
}
const flag = true
const xOrY = flag ? 'x' : 'y' // inferred type is 'x' | 'y'
const t: T = { xOrY }

Expected behavior:

The code should type check.

Actual behavior:

The last line is flagged with an error:

Type '{ xOrY: string; }' is not assignable to type '{ xOrY: "x" | "y"; }'.
  Types of property 'xOrY' are incompatible.
    Type 'string' is not assignable to type '"x" | "y"'.

It can be fixed by giving xOrY a type annotation to say that it has type "x" | "y", but the compiler seems to have already inferred that it has this type (based on what atom-typescript's show-types-on-hover feature is telling me), so that doesn't seem like it should be necessary.

When the union is of non-string literal types, there is no such error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions