UNPKG

@ayonli/jsext

Version:

A JavaScript extension package for building strong and modern applications.

68 lines (67 loc) 2.86 kB
/** * Functions for parsing JSONs to specific structures. * @module */ import { Constructor } from "./types.ts"; /** * Converts a JSON string into an object of the given type. * * The type can be `String`, `Number`, `BigInt`, `Boolean`, `Date`, `Array`, `Object` or any * class constructor (including Error types). If the class has a static * `fromJSON(data: any): T` method, it will be invoked to create the instance (unless the * parsed `data` is `null`, which will be skipped without further processing). * * This function generally does not perform loose conversion between types, for example, * `parseAs('"123"', Number)` will not work, it only reverses to the same type before the * data are encoded. * * However, for compatibility support, there are some exceptions allowed, which are: * * - `string` => `Date` * - `number` or `string` => `bigint` * - `array` => `Buffer` or `TypedArray` (e.g. `Uint8Array`), when the data only contains * integers. * - `object` => `Buffer` or `TypedArray` (e.g. `Uint8Array`), if the data are encoded by * `JSON.stringify()`. * - customized in `fromJSON()` * * If the data cannot be converted to the given type, this function returns `null`. */ export declare function parseAs(text: string, type: StringConstructor): string | null; export declare function parseAs(text: string, type: NumberConstructor): number | null; export declare function parseAs(text: string, type: BigIntConstructor): bigint | null; export declare function parseAs(text: string, type: BooleanConstructor): boolean | null; export declare function parseAs<T>(text: string, type: Constructor<T> & { fromJSON?(data: any): T; }): T | null; /** * Converts the data into the given type. * * This function is primarily used in {@link parseAs} and shares the same conversion rules, but it * can be used in other scenarios too, for example, inside the `fromJSON` function. */ export declare function as(data: unknown, type: StringConstructor): string | null; export declare function as(data: unknown, type: NumberConstructor): number | null; export declare function as(data: unknown, type: BigIntConstructor): bigint | null; export declare function as(data: unknown, type: BooleanConstructor): boolean | null; export declare function as<T>(data: unknown, type: Constructor<T> & { fromJSON?(data: any): T; }): T | null; /** * A decorator to instruct that the target property in the class is of a specific type. * * When parsing JSON via {@link parseAs}, this property is guaranteed to be of the given type. * * **NOTE:** This decorator only supports TypeScript's `experimentalDecorators`. * * @example * ```ts * import { type } from "@ayonli/jsext/json"; * * class Example { * \@type(Date) * date: Date; * } * ``` */ export declare function type(ctor: Constructor<any>): PropertyDecorator;