Middle
Have you ever used discriminant unions and type guards? What built-in type guards do you know?
sobes.tech AI
Answer from AI
Discriminated unions and type guards are powerful TypeScript tools for working with union types, allowing safe determination of a specific type within a union.
Discriminated unions are type unions where each type has a common literal key (for example, a type field), which can be used to unambiguously identify the specific type.
Type guards are functions or constructs that check the type of a variable at runtime and narrow the type for the compiler.
Built-in type guards in TypeScript include:
typeof— for primitives (string,number,boolean)instanceof— to check class membershipin— to check for the presence of a property in an object
Example of a discriminated union and type guard:
interface Square {
kind: 'square';
size: number;
}
interface Circle {
kind: 'circle';
radius: number;
}
type Shape = Square | Circle;
function area(shape: Shape): number {
switch (shape.kind) {
case 'square':
return shape.size * shape.size;
case 'circle':
return Math.PI * shape.radius ** 2;
}
}
Here, kind is the discriminator, and switch acts as a type guard.
Using built-in type guards:
function isString(value: unknown): value is string {
return typeof value === 'string';
}
if (isString(someVar)) {
// here, someVar is of type string
}