4 April 2023
How to Use Type Guards in TypeScript
function isString(value: unknown): value is string {
return typeof value === 'string';
}
Once you have defined a type guard, you can use it to narrow down the type of a variable in your code. Here's an example:
function logLength(value: unknown) {
if (isString(value)) {
console.log(value.length);
} else {
console.log('Value is not a string.');
}
}
You can also create custom type guards for more complex types. Here's an example of a custom type guard for checking if an object has a ‘name’ property:
interface Person {
name: string;
age: number;
}
function hasNameProperty(value: unknown): value is Person {
return typeof value === 'object' && value !== null && 'name' in value;
}
function logPersonName(person: unknown) {
if (hasNameProperty(person)) {
console.log(person.name);
} else {
console.log('Value is not a person.');
}
}
Conclusion
In this how-to guide, I have explained how to use type guards in TypeScript, including defining a type guard, using a type guard, creating custom type guards, and using custom type guards. By using type guards, you can write more robust and error-free code in TypeScript.
Official Documentation:
For more information about using type guards in TypeScript, you can refer to the official TypeScript documentation:
TypeScript: https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types
I hope this guide helps you get started with using type guards in TypeScript.
We would recommend our course in TypeScript.
CONTACT
+44 (0)20 8446 7555
Copyright © 2023 JBI Training. All Rights Reserved.
JB International Training Ltd - Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS
Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us