Type Guards
4 methodsRuntime checks that narrow types in conditional branches.
typeof x === 'string'Narrow primitive types using the typeof operator. Recognized: 'string', 'number', 'boolean', 'bigint', 'symbol', 'undefined', 'object', 'function'.
Parameters
| Name | Type | Description |
|---|---|---|
| x | any | Value to narrow. |
Returns
boolean
Example
typescript
function len(x: string | number): number {
if (typeof x === 'string') {
return x.length; // x: string
}
return Math.abs(x); // x: number
}x instanceof ClassNarrow to an instance type by checking the prototype chain.
Parameters
| Name | Type | Description |
|---|---|---|
| x | any | Value to narrow. |
| Class | constructor | Class constructor to check against. |
Returns
boolean
Example
typescript
function handle(e: Error | Date) {
if (e instanceof Error) {
console.log(e.message); // e: Error
} else {
console.log(e.getTime()); // e: Date
}
}'key' in objNarrow a union type by checking for the presence of a property.
Parameters
| Name | Type | Description |
|---|---|---|
| key | string | Property name to check. |
| obj | object | Object to check. |
Returns
boolean
Example
typescript
type Cat = { meow: () => void };
type Dog = { bark: () => void };
function speak(animal: Cat | Dog) {
if ('meow' in animal) animal.meow(); // animal: Cat
else animal.bark(); // animal: Dog
}function isX(x: any): x is TUser-defined type guard. The 'x is T' return type predicate triggers narrowing when the function returns true.
Parameters
| Name | Type | Description |
|---|---|---|
| x | any | Value to test. |
Returns
x is T
Example
typescript
function isString(x: any): x is string {
return typeof x === 'string';
}
function upper(x: unknown) {
if (isString(x)) {
return x.toUpperCase(); // x: string
}
return String(x);
}