Is Class
The Is
class provides a set of utility methods for type checking in TypeScript. It includes checks for basic types like string, number, null, undefined, boolean, bigint, symbol, object, function, any, array, date, error, promise, falsy, and custom checks using Zod schemas. Additionally, it provides methods for checking the execution environment (browser or server).
Usage
Importing the Is Class
Creating an Instance
Or get from the singleton t
instance:
Methods
Instanceof Check
Be sure to call the class with new before passing it to the instanceof
method.
instanceof<T>(constructor: new (...args: any[]) => T, value: unknown): value is T
Checks if the value is an instance of a class.
Note: Make sure to set the
name
property in the class constructor to use this method, thename
property is used to check the class name.
Example:
Custom Check with of
of<T>(constructor: T, func: (value: T) => value is T): value is T
Checks if the value passes a custom check.
Example:
String Check
string(value: unknown): value is string
Checks if the value is a string.
Example:
Negative example:
Number Check
number(value: unknown): value is number
Checks if the value is a number.
Example:
Null Check
null(value: unknown): value is null
Checks if the value is null.
Example:
Undefined Check
undefined(value: unknown): value is undefined
Checks if the value is undefined.
Example:
Boolean Check
boolean(value: unknown): value is boolean
Checks if the value is a boolean.
Example:
BigInt Check
bigint(value: unknown): value is bigint
Checks if the value is a bigint.
Example:
Symbol Check
symbol(value: unknown): value is symbol
Checks if the value is a symbol.
Example:
Object Check
object(value: unknown): value is object
Checks if the value is an object.
Example:
Array Check
array(value: unknown): value is unknown[]
Checks if the value is an array.
Example:
Function Check
function(value: unknown): value is ((...args: unknown[]) => unknown) | Function
Checks if the value is a function.
Example:
Any Check
any(value: unknown): value is any
Always returns true.
Example:
Date Check
date(value: unknown): value is Date
Checks if the value is a Date.
Example:
Error Check
error(value: unknown): value is Error
Checks if the value is an Error.
Example:
Promise Check
promise(value: unknown): value is Promise<unknown>
Checks if the value is a Promise.
Example:
Falsy Check
falsy(value: unknown): value is Falsy
Checks if the value is falsy.
Example:
Schema Check
schema(schema: ZodTypeAny, value: unknown): value is ZodTypeAny
Checks if the value adheres to a Zod schema.
Example:
Of Check
of<T>(constructor: T, value: unknown): value is T
Checks if the value is an instance of a class or object.
Example:
Browser Check
browser(): boolean
Checks if the code is running in a browser.
Example:
Server Check
server(): boolean
Checks if the code is running without a browser.
Example: