Skip to content

TS Unable to detect duplicate keys in object when using variables + computed properties #29239

Closed
@joshburgess

Description

@joshburgess

TypeScript Version:

3.3.0-dev.201xxxxx

Search Terms:

computed properties, duplicate keys

Code

// type error, as expected
const foo1 = {
  Key1: 1,
  Key1: 2
}

// ok, let's try with computed properties
const Key1 = 'Key1'
const Key2 = 'Key2'

// no type error? widened type to `string`, maybe?
const foo2 = {
  [Key1]: 1,
  [Key1]: 2
}

// type error when literals are used
const foo3 = {
  ['Key1']: 1,
  ['Key1']: 2
}

// now, let's try with enums
enum TestEnum {
  Key1 = 'Key1',
  Key2 = 'Key2'
}

// no type error? widened type to `string`, maybe?
const foo4 = {
  [TestEnum.Key1]: 1,
  [TestEnum.Key1]: 2
}

Expected behavior:

I found some weirdness around how typescript treats computed properties & duplicate keys. I would expect it to detect duplicate keys when passed variables with specific type literals, whether created via constants or enum members.

Actual behavior:

Duplicate keys are not detected when variables are used as computed properties. This is particularly a problem when trying to use enum members, because there is no alternative way to use them as keys in an object.

Playground Link:

https://bit.ly/2TrDznF

Related Issues:

Possibly these:

#26208

#18596

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions