DEV Community 👩‍💻👨‍💻

Acid Coder
Acid Coder

Posted on • Updated on

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


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> / {[x in string]: T}

this is work as expected

more on github PR and release note

Top comments (0)

🤔 Did you know?

DEV has a variety of tags to help you find the content you like. Find and follow your favorite tags.