keyof { [ x: string ]: any } returns string | number type #47200
Copy link
Copy link
Closed
Description
Bug Report
🔎 Search Terms
keyof returns string or number
🕗 Version & Regression Information
Still exists in TypeScript v4.5.4
Was discovered in TypeScript v4.1.2
- This is a case of an incorrect type being returned
- This changed between versions 2.1.0 and 4.1.2
- This is the behavior in every version I tried
- I was unable to test this on prior versions because I don't have time to test every possible version of TS
⏯ Playground Link
Playground link with relevant code
💻 Code
type X = keyof { [y: string]: any } // should return type `string`Note that the below code DOES work as expected, only string has the issue
type A = keyof { [b: number]: any } // returns type `number` as expected🙁 Actual behavior
The code sample is returning type string | number
🙂 Expected behavior
The code sample should returning type string
The documentation here explains that string should be what is returned:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels
Activity
IllusionMH commentedon Dec 20, 2021
It was charged since 2.1. See current Handbook content https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#the-keyof-type-operator
And corresponding update https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#support-number-and-symbol-named-properties-with-keyof-and-mapped-types
Dan503 commentedon Dec 20, 2021
So is it possible to resolve the string type conflict at all?
I can't pass type
string | numberinto something expecting only type string :(IllusionMH commentedon Dec 20, 2021
Depends on the case. Can be
T & string,Exclude<T, number>, condition type etc.Dan503 commentedon Dec 20, 2021
This ended up working for me :)
I'll close this issue since this was an intentional change by the maintainers of TS.