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

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


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



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Acid Coder

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