Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTypeScript

Why Object.keys returns string[]

See why Object.keys returns string[] and use an explicit list of typed keys to index a known set of properties.

You loop over the keys of a typed object, index the object with each key, and tsc refuses. The object has the two properties you wrote and no others. TypeScript still treats the key as any string.

type Settings = { theme: string; fontSize: number }
const settings: Settings = { theme: 'dark', fontSize: 16 }

for (const key of Object.keys(settings)) {
  console.log(key, settings[key])
}

Running tsc --noEmit --strict trap.ts prints error TS7053: Element implicitly has an 'any' type, because a string can't index Settings. Object.keys returns the object's own enumerable string keys, and Settings has no index signature for a string. The compiler cannot know your object has no extra keys, so any narrowing has to come from you.

Why the key is a string

A type lists the properties a value must have. It does not promise the value has no others. A variable holding an object with extra properties can be passed where the smaller type is expected.

type Point = { x: number; y: number }

function describe(p: Point) {
  for (const key of Object.keys(p)) {
    console.log(key)
  }
}

const labelled = { x: 1, y: 2, label: 'origin' }
describe(labelled)

This compiles, and it prints x, y and label. Point requires two properties. The object passed to describe has three, so Object.keys returns all three. If it were typed (keyof Point)[] using keyof, the compiler would call label an x or a y.

List the keys you need

When you know which settings you want to print, list them and let TypeScript check each key.

const settingKeys = ['theme', 'fontSize'] satisfies (keyof Settings)[]

for (const key of settingKeys) {
  console.log(key, settings[key])
}

Keep the Settings type and settings value from the first example. Replace its loop with this one to print theme dark and fontSize 16. A typo such as 'fontsize' fails at the key list.

Maintain the list when you add a setting you want to print. If you need the actual values of an object supplied by a caller, use Object.entries and validate the values before using them.