microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.19k stars 12.38k forks source link

Inconsistency between element access and object destruction #59571

Open KermanX opened 1 month ago

KermanX commented 1 month ago

πŸ”Ž Search Terms

destruct object

πŸ•— Version & Regression Information

Before v4.4.4, index expression in element access was also not inferred as const. So this issue starts from v4.4.4. Reproducible in Nightly build.

⏯ Playground Link

https://www.typescriptlang.org/play/#code/DYUwLgBAdhC8EEYIEMDOEDGB7KqwChtdIs4IBvFBALggCIE6V0i8IBffQnNgDzKwBtAAbIAJOSjthAXXwB6eRGUQAegH5uxChBHjJ0mbQCeHAfiA

πŸ’» Code

let n = 1 as const
const o = { a1: "abcd" }

const x = o[`a${n}`]
//    ^? : string
const { [`a${n}`]: y } = o
//           ^? Errors: Type '{ a1: string; }' has no matching index signature for type 'string'.(2537)

πŸ™ Actual behavior

`a${n}` in object destruction not inferred as const ("a1")

πŸ™‚ Expected behavior

`a${n}` in object destruction should be inferred as "a1", just like the one in element access.

Additional information about the issue

A possible workaround is to add as const after `a${n}`. I think the main problem is the inconsistency between element access and object destruction, which is confusing.

sparecycles commented 1 month ago

Another destructuring inconsistency, (I'm not sure if the fix would be related, but cross-linking just in case).

https://github.com/microsoft/TypeScript/issues/59581