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.

Previous:
How I make my Vite dev server experience faster October 22, 2024 Node, React, JavaScript
Next:
brotli_static in Nginx November 8, 2024 Linux, Nginx
Related by category:
You don't need a context or state manager for TanStack Query in scattered React components January 2, 2026 JavaScript
Always run biome migrate after upgrading biome August 16, 2025 JavaScript
Video to Screenshots app June 21, 2025 JavaScript
Starting a side project: PissueTracker March 16, 2025 JavaScript
Related by keyword:
In TypeScript, how to combine known and unknown keys to an object July 3, 2024 JavaScript
Simple object lookup in TypeScript June 14, 2024 JavaScript