Skip to content

Inference issue: using constants with unique string literal types as record fields #15121

Closed
@liam-goodacre-hpe

Description

@liam-goodacre-hpe

TypeScript Version: 2.2.2

Code

const A = 'A' // infers `A : 'A'`
const B = 'B' // infers `B : 'B'`

const n0 = { A, B } // infers `n0 : {A: string, B: string}`
const n1 = { 'A': A, B } // infers `n1 : {'A': string, B: string}`
const n2 = { [A]: A, B } // infers `n2 : {[x: string]: string, B: string}`
const n3 = { [A as 'A']: A, B } // infers `n3 : {[x: string]: string, B: string}`
const n4 = { ['A' as 'A']: A, B } // infers `n4 : {[x: string]: string, B: string}`

Expected behavior:
All n_ should have the same type as n0 - i.e. with a key A.

Actual behavior:
Record type gains an index [x: string]: string.

Background:
I have constants in a namespace that I want to use as field names in a record.

namespace X {
  export const A = 'A'
}
const foo = { [X.A]: 'example' } // infers `foo : { [x: string]: string }`

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