Type guards
Type guards allow you to narrow the type of a value:
function doThing(x: number | string) { if (typeof x === 'string') { // `x` is string return x.substring(1); }
// `x` is number return x * x;}
Primitive
Guards for primitive types.
isBoolean
Checks whether a value is boolean
.
function isBoolean(value: unknown): value is boolean;
isNull
Checks whether a value is null
.
function isNull(value: unknown): value is null;
isNumber
Checks whether a value is a number
.
Does not consider NaN
a valid value
function isNumber(value: unknown): value is number;
isString
Checks whether a value is a string
.
function isString(value: unknown): value is string;
isUndefined
Checks whether a value is undefined
.
function isUndefined(value: unknown): value is undefined;
Nullish
Guards for nullish types.
isNullish
Checks whether a value is null
or undefined
.
function isNullish(value: unknown): value is Nullish;
isDefined
Checks whether a value is not null
or undefined
.
function isDefined<T>(value: T | Nullish): value is NonNullable<T>;
Array
Guards for array types.
isNonEmptyArray
Checks whether an array is not empty.
function isNonEmptyArray<T>(value: T[]): value is [T, ...T[]];
Promise
Guards for Promise related types.
isFulfilled
Checks whether a result from Promise.allSettled
is fulfilled
function isFulfilled<T>(result: PromiseSettledResult<T>): result is PromiseFulfilledResult<T>;
const results = await Promise.allSettled(promises);const fulfilledValues = results.filter(isFulfilled).map(result => result.value);
isRejected
Checks whether a result from Promise.allSettled
is rejected.
function isRejected(result: PromiseSettledResult<unknown>): result is PromiseRejectedResult;
const results = await Promise.allSettled(promises);const rejectionReasons = results.filter(isRejected).map(result => result.reason);