-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Inconsistency in inferring string indexers #29423
Comments
Yikes. As far as I know, TS doesn't do compile-time string interpolation. This is more a feature request than a bug report. To TS, |
Duplicate of #14584 |
Thank you both @RyanCavanaugh and @AnyhowStep for the reply. Both #14584, and #13969 referenced within, have not been updated in close to two years. What's the official stance on this request? This seems to be to be consistent with the way TS currently works. Is there any workaround, to avoid having TS complain about this issue? |
Does this work? testObject[str === 'X' ? 'movX' : 'movY'] *= 33; If not, you can probably force the key. testObject[(str === 'X' ? 'movX' : 'movY') as keyof TestInterface] *= 33; |
Thanks for the suggestion, I tried the following, and it works: const key = `mov${str}` as keyof TestInterface;
testObject[key] *= 33; …except that it doesn't, really. The above was a simplified example, as soon as interface TestInterface {
movX: number,
movY: number,
anExtraKey: string
}
const key = `mov${str}` as keyof TestInterface; // is now "movX" | "movY" | "anExtraKey" |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
TypeScript Version: 3.2.2
Search Terms: String index
Code
Expected behavior:
TypeScript correctly recognizes that
testObject[`mov${str}`]
can only betype: number
becausestr
can only betype: "X" | "Y"
.Actual behavior:
Typescript complains:
Playground Link:
http://www.typescriptlang.org/play/#src=interface%20TestInterface%20%7B%0D%0A%20%20movX%3A%20number%2C%0D%0A%20%20movY%3A%20number%0D%0A%7D%0D%0A%0D%0Alet%20str%3A%20%22X%22%20%7C%20%22Y%22%20%3D%20%22Y%22%3B%0D%0Aconst%20testObject%3A%20TestInterface%20%3D%20%7B%0D%0A%20%20movX%3A%200%2C%0D%0A%20%20movY%3A%200%0D%0A%7D%3B%0D%0A%0D%0AtestObject%5B%60mov%24%7Bstr%7D%60%5D%20*%3D%2033%3B%0D%0AtestObject%5B'movX'%5D%20*%3D%2034%3B
Also, this is just a short example, I don't want to declare a string indexer, because my real-world object is more complex than the one shown in the example.
The text was updated successfully, but these errors were encountered: