Typescript Caveat 2: keyof {[x:string]:string} is string | number

Acid Coder
Oct 4, 2022
type A = {[x:string]:string} 
type B = keyof A // string | number
// ^?
const A:A = {a:"abc",[1]:"xyz"}type C = keyof A & string // string
// ^?

playground

normally this will not cause any issue, because number key in javascript will coerce into string key

however this may cause issue if we are doing some type manipulation

to solve this we can intersect it with string or set keyofStringsOnly to true in the ts config

or just use Record<string, T> or{[x in string]: T}

this is work as expected

more on github PR and release note

--

--

Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)