DEV Community

Acid Coder
Acid Coder

Posted on • Updated on

Typescript WTF Moments 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
//   ^?
Enter fullscreen mode Exit fullscreen mode

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

Latest comments (0)