Skip to content

Conditional types: cannot extend a string singleton type #30465

Closed
@mgol

Description

@mgol

TypeScript Version: 3.4.0-dev.20190316

Search Terms:

  • extends string literal
  • conditional string singleton

Code

type Foo = {
    [T in string]: T extends 'a' ? number : string;
}
let foo: Foo = { a: 1, b: 'c' } as const;
foo['a' as 'a'] = 2 as const;
foo['a' as const] = 2 as const;

Expected behavior:

The code should not emit errors. TS should not expand the type of 'a' to string for the purpose of using this type in a conditional with the extends 'a' condition.

Actual behavior:

The attached code errors in all last 3 lines. It seems no matter how hard I try to tell the compiler I don't want to expand the type of 'a' into string it still does it.

Playground Link:

The above example uses TS 3.4 features so Playground won't work. But here's a version without as const that's parseable on the playground:
https://www.typescriptlang.org/play/#src=type%20Foo%20%3D%20%7B%0D%0A%20%20%20%20%5BT%20in%20string%5D%3A%20T%20extends%20'a'%20%3F%20number%20%3A%20string%3B%0D%0A%7D%0D%0Alet%20foo%3A%20Foo%20%3D%20%7B%20a%3A%201%2C%20b%3A%20'c'%20%7D%3B%0D%0Afoo%5B'a'%20as%20'a'%5D%20%3D%202%3B%0D%0A

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions