Skip to content

Typescript object constants

13 December 2023

No need for type unsafe Object.keys(). You can now access the keys of an object safely.

typescript
const MANUFACTURERS = {
  McLaren: {
    ID: 12,
    location: "United Kingdom",
  },
  "Mercedes-Benz": {
    ID: 34,
    location: "United Kingdom",
  },
  Ferrari: {
    ID: 56,
    location: "Italy",
  },
  "Red Bull": {
    ID: 78,
    location: "Austria",
  },
} as const;

type Manufacturer = keyof typeof MANUFACTURERS;

let m: Manufacturer;
for (m in MANUFACTURERS) {
  /* m is of type "McLaren" | "Mercedes-Benz" | ... etc. */
  console.log(MANUFACTURERS[m].location);
}