javascriptreactjstypescripttypescript-eslint

how to get typescript duplicate property error?


I'm using typescript version 4.9.5 and i want to use an enum as keys of an object. for example:

enum TestEnum {
  value1 = 'value1',
  value2 = 'value2',
}

const variable: {[key in TestEnum]: number} = {
  [TestEnum.value1]: 5,
  [TestEnum.value2]: 7,
  [TestEnum.value1]: 9,
}

Problem is that in this version i wont get typescript duplicate property error. i know that in newer versions (> 5.1) it's handled. but i can't use another version.and i know if i use value1 instead of [TestEnum.value1] it will be handled by ts. but i don't want use enum value directly. Is there any other way to solve this problem?


Solution

  • There is no way to do what you're looking for in TypeScript <=4.9.5. The feature of detecting duplicate enum property keys was added in 5.0.

    As @Bergi commented, you could write a custom typescript-eslint rule to detect this for you. It could use lint rule type information to look at the static types of dynamic keys in objects and report when multiple refer to the same enum key.

    ...but it would be much better if you could upgrade to a newer version of TypeScript that has this feature. Your lint rule would essentially be a duplication of a newer TypeScript feature, and would likely be buggy. It's actually quite hard to get duplicate property key checking done right.