In this tutorial, we'll explore Type Assertions and Type Guards in TypeScript. Type Assertions allow you to tell the compiler "trust me, I know what I'm doing," and Type Guards help you narrow down the type of an object within a certain scope.
By following this tutorial, you'll learn how to use these features to create more robust and safe TypeScript code.
Prerequisites: Familiarity with TypeScript and basic programming concepts like variables, types, and functions.
In TypeScript, type assertions are a way to tell the TypeScript compiler that you are sure about the type of a variable. This does not restructure or reformat the data in any way, but it does stop TypeScript from inferring the type.
Syntax:
let someVariable: any = "this is a string";
let strLength: number = (<string>someVariable).length;
Or:
let someVariable: any = "this is a string";
let strLength: number = (someVariable as string).length;
Type guards allow you to narrow down the type of an object within a certain scope. This is done by using type-checking functions that return a boolean indicating whether the specific type matches.
Syntax:
function isString(test: any): test is string{
return typeof test === "string";
}
function example(foo: any){
if (isString(foo)){
console.log("It's a string!");
console.log(foo.length); // string function
}
}
let someVariable: any = "Hello World";
let strLength: number = (<string>someVariable).length;
console.log(strLength); // outputs: 11
Here, we are asserting that someVariable
is a string, so we can use the .length
property associated with strings.
function isNumber(x: any): x is number {
return typeof x === "number";
}
let item: any = 10;
if (isNumber(item)) {
console.log(item.toFixed(2)); // outputs: "10.00"
}
In this example, the isNumber
function is a type guard. When we use it in the if
statement, TypeScript knows that item
is a number in that if block.
In this tutorial, we've learned about type assertions and type guards in TypeScript. We've seen how type assertions allow us to override TypeScript's inferred types in any way we want, and how type guards can help us narrow down types within a certain scope.
For further study, I recommend exploring the official TypeScript documentation and practicing with more complex examples.
Solutions
function isStringArray(value: any): value is string[] {
return Array.isArray(value) && value.every(item => typeof item === 'string');
}
let arr = ['hello', 'world'];
if (isStringArray(arr)) {
console.log(arr.join(' ')); // Outputs: "hello world"
}
let str: any = "4";
let num: number = <number><unknown>str;
console.log(Math.sqrt(num)); // Outputs: 2
These exercises should help you get a practical understanding of how to use type assertions and type guards in TypeScript. Keep practicing and exploring these concepts to gain a deeper understanding.