DEV Community

Jhosep
Jhosep

Posted on

Const Assertion

Strive to use const assertion (as const):

  1. type is narrowed

  2. object gets readonly properties

  3. array becomes readonly tuple

let's see an example:

// ❌ Avoid declaring constants without const assertion
const BASE_LOCATION = { x: 50, y: 130 }; // Type { x: number; y: number; }
BASE_LOCATION.x = 10;
const BASE_LOCATION = [50, 130]; // Type number[]
BASE_LOCATION.push(10);

// ✅ Use const assertion
const BASE_LOCATION = { x: 50, y: 130 } as const; // Type '{ readonly x: 50; readonly y: 130; }'
const BASE_LOCATION = [50, 130] as const; // Type 'readonly [10, 20]'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)