TypeScript tip: Restrict object keys to specific types


I’ve been programming in TypeScript for a couple of years.

There are some syntax details that I can never remember exactly. So in short, this is how to do it:

type Bird = {
  size: number
}

type BirdRepository = {
  [id: number]: Bird
}

const birds: BirdRepository = {}

birds[12] = { size: 4 } // correct

Then, when you try to use a type that doesn’t comply, it raises an error:

birds['abc'] = { size: 4 }
//    ☝️☝️☝️ warning!
// Element implicitly has an 'any'
// type because index expression is
// not of type 'number'.(7015)

Leave a Reply

Your email address will not be published. Required fields are marked *