Type Widening in TypeScript 🏷️TS

Type Widening in TypeScript 🏷️TS

Type widening is TypeScript's process of inferring a broader type set from a single constant value during static analysis.

Control Methods

// 1. Explicit Type Annotation
const v: {x: 1|3|5} = {
  x: 1
}; // Type is { x: 1|3|5 }

// 2. Const Assertion
const v1 = {
  x: 1,
  y: 2
}; // Type is { x: number; y: number; }

const v2 = {
  x: 1 as const,
  y: 2
}; // Type is { x: 1; y: number; }

const v3 = {
  x: 1,
  y: 2
} as const; // Type is { readonly x: 1; readonly y: 2; }

// Arrays and Tuples
const arr1 = [1, 2, 3]; // number[]
const arr2 = [1, 2, 3] as const; // readonly [1, 2, 3]

Ways to Control Widening

  1. Explicit type annotations
  2. Context (function parameters)
  3. const assertions
  4. as const for literal values
  5. Tuple type assertions

When to Use Each Approach

References

Notes

🔍 #typescript #type-widening #type-inference #const-assertions


From: Vanderkam-Effective TypeScript