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
- Explicit type annotations
- Context (function parameters)
constassertionsas constfor literal values- Tuple type assertions
When to Use Each Approach
- Use explicit annotations for intended type flexibility
- Use
as constfor true constants - Use context when type is determined by usage
- Use
constassertions for precise literal types - Use tuple assertions for fixed-length arrays
Related
- Type Inference
- Literal Types
- Const Assertions
- Type Narrowing
- Tuple Types
References
- Effective TypeScript
Notes
- Widening affects static analysis only
- Check inferred types in editor
- Balance between flexibility and precision
- Consider runtime needs when choosing approach
🔍 #typescript #type-widening #type-inference #const-assertions