Why does TypeScript allow duplicate indexed properties in const declaration?

Viewed 86

When you declare a constant in TypeScript with duplicate static property names, it gives you a helpful error.

const doesNotCompile1 = { a: 1, a: 2 };
const doesNotCompile2 = { ['a']: 1, ['a']: 2 };
const doesNotCompile3 = { a: 1, ['a']: 2 };

An object literal cannot have multiple properties with the same name in strict mode. (1117)

Duplicate identifier 'a'. (2300)

If you declare a constant string literal, and do it against a static constant, you get the same error message.

const a = 'a';
const doesNotCompile4 = { a: 1, [a]: 2 };
const doesNotCompile5 = { ['a']: 1, [a]: 2 };

However, using the same constant as two separate properties does not cause a compilation error.

const a = 'a';
const b = 'a';
const compiles1 = { [a]: 1, [a]: 2 };
const compiles2 = { [a]: 1, [b]: 2 };

Why does TS allow this? This seems like a bug to me, but so many things have and turned out to be by design.

TS Playground

0 Answers
Related