To Class
The To
class provides a set of utility methods for type casting in TypeScript. It includes casts for basic types like string, number, boolean, bigint, symbol, object, function, any, array, date, error, promise, and custom casts using Zod schemas.
Usage
Importing the To Class
import { To } from "@mvdlei/tzod/to";
Creating an Instance
const to = new To();
Or get from the singleton t
instance:
import { t } from "@mvdlei/tzod";
const to = t.to;
Methods
String Cast
string(value: unknown): string
Casts the value to a string.
Example:
const result = to.string(123);
// ^ "123"
Number Cast
number(value: unknown): number
Casts the value to a number.
Example:
const result = to.number("123");
// ^ 123
Boolean Cast
boolean(value: unknown): boolean
Casts the value to a boolean.
Example:
const result = to.boolean(0);
// ^ false
BigInt Cast
bigint(value: unknown): bigint
Casts the value to a bigint.
Example:
const result = to.bigint(123);
// ^ 123n
Symbol Cast
symbol(value: unknown): symbol
Casts the value to a symbol.
Example:
const result = to.symbol("symbol");
// ^ Symbol("symbol")
Url Cast
url(value: unknown): URL
Casts the value to a URL.
Example:
const result = to.url("https://example.com");
// ^ URL { href: "https://example.com", ... }
Promise Cast
promise<T>(value: unknown): Promise<T>
Casts the value to a Promise.
Example:
const result = to.promise("value");
// ^ Promise { "value" }
Date Cast
date(value: unknown): Date
Casts the value to a Date.
Example:
const result = to.date("2021-01-01");
// ^ Date { "2021-01-01T00:00:00.000Z" }
Error Cast
error(value: unknown): Error
Casts the value to an Error.
Example:
const result = to.error("Something went wrong");
// ^ Error { "Something went wrong" }
Readonly Cast
readonly<T>(value: T): Readonly<T>
Casts the value to a Readonly.
Example:
const result = to.readonly({ key: "value" });
// ^ readonly { key: "value" }
Array Cast
array<T>(value: unknown): T[]
Casts the value to an array.
Example:
const result = to.array("value");
// ^ ["value"]