Web Development
TypeScript
Subjective
Oct 04, 2025
Explain control flow analysis and type narrowing in TypeScript.
Detailed Explanation
TypeScript analyzes code flow to narrow types based on conditions, assignments, and type guards.
Type Narrowing with typeof:
function padLeft(padding: number | string, input: string): string {
if (typeof padding === 'number') {
// TypeScript knows padding is number here
return new Array(padding + 1).join(' ') + input;
}
// TypeScript knows padding is string here
return padding + input;
}
Truthiness Narrowing:
function getUserName(user: { name?: string }) {
if (user.name) {
// TypeScript knows user.name is string (not undefined)
return user.name.toUpperCase();
}
return 'Anonymous';
}
Discriminated Unions:
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; sideLength: number };
function getArea(shape: Shape) {
switch (shape.kind) {
case 'circle':
// TypeScript knows shape has radius property
return Math.PI * shape.radius ** 2;
case 'square':
// TypeScript knows shape has sideLength property
return shape.sideLength ** 2;
}
}
Custom Type Guards:
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function processValue(value: unknown) {
if (isString(value)) {
// TypeScript knows value is string
console.log(value.toUpperCase());
}
}
Benefits:
• Eliminates need for type assertions
• Provides compile-time safety
• Enables precise type checking
• Improves code reliability.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts