Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mapped types allow numeric constraint types #18346

Closed
wants to merge 2 commits into from

Commits on Sep 8, 2017

  1. Mapped types allow numeric constraint types

    Mapped types now allow the constraint type to be `number`, a union of
    numeric literal types or an enum. When it is possible to treat an enum
    as a union of numeric literal types, the compiler does so.
    
    Numeric literal types create a property with the string form of the
    name. `number` and non-union enums create a number index signature on
    the mapped type. This enables most numeric enums to be used as the
    constraint type in mapped types:
    
    ```ts
    // @strict: true
    enum Nums { A, B }
    type NumBool = { [K in Nums]: boolean }
    let nb: NumBool = { '0': true, [1]: false }
    nb[Nums.A] = false
    ```
    
    Note that any expression with the right literal type can be used to
    index into the resulting mapped type. This means that other enum entries
    are fine as long as they are in range of the original enum:
    
    ```ts
    enum Nums2 { Aleph, Bet, Gimel }
    nb[Nums.Aleph] = true // fine, equivalent to Nums.A and 0 and '0'
    nb[Nums.Gimel] = false // error only with 'strict': true
    ```
    
    You can also manually create unions that mix string and number literal
    types:
    
    ```ts
    type Mixed = 0 | 1 | 'a' | '1'
    type MixNum = { [K in Mixed]: number }
    ```
    
    If you do this be aware that if a number and a string literal conflict
    after the number has been converted to string, then both will be
    dropped from the mapped type:
    
    ```ts
    let mn: MixNum = { [0]: 8, [1]: 8, 'a': 8 }
                               ~~~~~~
    Object literal may only specify known properties, and '[1]' does not exist in type 'MixNum'
    ```
    
    Non-union enums and `number` are just equivalent to a number index signature;
    `{ [K in number]: any }` is equivalent to `{ [n: number]: any }`.
    sandersn committed Sep 8, 2017
    Configuration menu
    Copy the full SHA
    bd2c386 View commit details
    Browse the repository at this point in the history
  2. Configuration menu
    Copy the full SHA
    3cd24b7 View commit details
    Browse the repository at this point in the history