Search⌘ K

Keys with Constants and Symbols

Explore how to use constants and symbols as keys in TypeScript index signatures to avoid errors and enforce key constraints. Understand the improvements in TypeScript 2.7 that allow defining fields with constants and symbols, and learn through practical examples how this enhances type safety and avoids common mistakes.

We'll cover the following...

Constant

Version 2.7 brings the possibility of accessing a property using a constant and symbol. This is a minor improvement because, before 2.7, it was possible to access (read and write) a constant or symbol, but not to define a field in an interface or type.

TypeScript 3.3.4
const Foo = "Foo"; // Constant value
const Bar = "Bar"; // Constant value
const Zaz = "Zaz"; // Constant value
const objectWithConstantProperties = { [Foo]: 100, [Bar]: "hello", [Zaz]: () => {} };
let a12: number = objectWithConstantProperties[Foo];
let b2334: string = objectWithConstantProperties[Bar];
console.log(a12);
console.log(b2334);

The example defined three ...