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:
Switching from Next.js to Vite + wouter July 28, 2023 JavaScript
How to SSG a Vite SPA April 26, 2025 JavaScript
An ideal pattern to combine React Router with TanStack Query November 18, 2024 JavaScript
swr compared to @tanstack/react-query August 30, 2024 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