This tutorial aims to introduce assertions and type guards in TypeScript. These are powerful features that help in ensuring type safety and preventing common errors.
By the end of this tutorial, you will be able to use assertions and type guards effectively to enhance the quality of your TypeScript code by preventing potential errors.
Basic knowledge of TypeScript is required to follow along with this tutorial.
In TypeScript, an assertion is a way to tell the compiler "trust me, I know what I'm doing." It doesn't change the runtime behavior of the program but helps in type checking during development.
let someVar: any = "hello";
let strLength: number = (<string>someVar).length;
In the above example, <string>someVar
is a type assertion. We are telling the compiler that someVar
is a string.
Type guards are expressions that perform a runtime check and narrow down the type of a variable within a certain scope.
function isNumber(x: any): x is number {
return typeof x === "number";
}
In the above example, x is number
is a type guard. If the function returns true, TypeScript compiler will know that x
is a number within that if-block.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
In this example, we're asserting that someValue
is a string. So, we can access the .length
property which is specific to string type.
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
}
}
example("hello world");
In this example, isString(foo)
is a type guard. If it returns true, then within the if-block, TypeScript knows that foo
is a string.
In this tutorial, we learned about assertions and type guards in TypeScript. We learned how to use assertions to tell the compiler to treat a variable as a specific type. We also learned how to use type guards to check the type of a variable at runtime.
Use type guard to write a function that takes an array of strings and numbers and returns a new array with only strings.
Use assertion to write a function that takes an object with an any
type and a string as a key, and returns the length of the value of that key.
function filterStringsFromMixedArray(arr: (string | number)[]): string[] {
return arr.filter((item): item is string => typeof item === 'string');
}
In this solution, we're using a type guard item is string
to filter out the strings from the array.
function getLengthOfValue(obj: any, key: string): number {
return (obj[key] as string).length;
}
In this solution, we're using an assertion to tell the compiler that obj[key]
is a string, so we can use the length
property.
These exercises should help solidify your understanding of assertions and type guards. Try to use these concepts in your own TypeScript code to enhance type safety.