This one always confused me but by blogging about it, hopefully, it will stick.

This does NOT work in TypeScript:


const person = {
  firstName: "peter",
  lastName: "bengtsson",
  state: "happy"
}

const keys = Object.keys(person)
const randomKey = keys[Math.floor(Math.random() * keys.length)];
const value = person[randomKey]

It works in JavaScript, but in TypeScript you get an error on the last line (from the person[randomKey]):


Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ firstName: string; lastName: string; state: string; }'.
  No index signature with a parameter of type 'string' was found on type '{ firstName: string; lastName: string; state: string; }'.

The solution

Without further ado:


const person = {
  firstName: "peter",
  lastName: "bengtsson",
  state: "happy"
}

type Key = keyof typeof person
const keys = Object.keys(person) as Key[]
const randomKey = keys[Math.floor(Math.random() * keys.length)];
const value = person[randomKey]

If you hover the that randomKey on the second to last line, the tooltip will say const randomKey: "firstName" | "lastName" | "state".

TypeScript Playground here.

Comments

Your email will never ever be published.

Related posts