advanced#TypeScript#Type Guards#Narrowing
Mastering TypeScript Type Guards
Learn about TypeScript type guards and how to use them to narrow types.
Introduction to Type Guards
In TypeScript, a type guard is a way to narrow the type of a value within a specific scope.
Step 1: Define a Type Guard
Create a new file called type-guards.ts and add the following code:
function isString<T>(value: T): value is string {
return typeof value === 'string';
}
This function is a type guard that checks if a value is a string.
Step 2: Use the Type Guard
Add the following code to the type-guards.ts file:
const value: string | number = 'hello';
if (isString(value)) {
console.log(value.toUpperCase());
}
This code uses the isString type guard to narrow the type of the value variable.
Step 3: Create a More Complex Type Guard
Add the following code to the type-guards.ts file:
interface Bird {
fly(): void;
}
interface Fish {
swim(): void;
}
function isBird<T>(value: T): value is Bird {
return (value as Bird).fly !== undefined;
}
This code defines a type guard that checks if a value is a Bird.