One useful feature in TypeScript is type guards, which allow you to narrow down the type of a value within a type hierarchy. This can be especially useful when working with complex data structures or when interacting with external libraries.
To create a type guard in TypeScript, you can use the typeof operator or the instanceof operator. The typeof operator allows you to check if a value is of a certain primitive type, such as number, string, or boolean. The instanceof operator, on the other hand, allows you to check if a value is an instance of a particular class or constructor function.
Here is an example of using the typeof operator to create a type guard:
function isNumber(x: any): x is number {
return typeof x === 'number';
}
let x = 4;
if (isNumber(x)) {
console.log(x.toFixed(2)); // 4.00
}
In this example, the isNumber function is a type guard that checks if the value passed to it is of type number. If it is, the function returns true, and the type of x within the if block is narrowed down to number. This allows us to use the toFixed method on x, which is only available on number values.
Here is an example of using the instanceof operator to create a type guard:
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
function isPoint(x: any): x is Point {
return x instanceof Point;
}
let x = new Point(0, 0);
if (isPoint(x)) {
console.log(`(${x.x}, ${x.y})`); // (0, 0)
}
In this example, the isPoint function is a type guard that checks if the value passed to it is an instance of the Point class. If it is, the function returns true, and the type of x within the if block is narrowed down to Point. This allows us to access the x and y properties on x, which are only available on Point instances.
Type guards are a powerful tool in TypeScript that can help you write safer and more reliable code. By narrowing down the type of a value within a type hierarchy, you can avoid runtime errors and take advantage of the type-checking features of TypeScript.
Top comments (0)