DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

1 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay