@deepkit/core
Version:
Deepkit core library
284 lines (283 loc) • 9.81 kB
TypeScript
/**
* Makes sure the error once printed using console.log contains the actual class name.
*
* @example
* ```
* class MyApiError extends CustomerError {}
*
* throw MyApiError() // prints MyApiError instead of simply "Error".
* ```
*/
export declare class CustomError extends Error {
name: string;
constructor(...args: any[]);
}
/**
* @internal
*/
export interface CustomError {
cause?: unknown;
}
export interface ClassType<T = any> {
new (...args: any[]): T;
}
export type AbstractClassType<T = any> = abstract new (...args: any[]) => T;
export type ExtractClassType<T> = T extends AbstractClassType<infer K> ? K : never;
/**
* Returns the class name either of the class definition or of the class of an instance.
*
* Note when code is minimized/uglified this output will change. You should disable in your compile the
* className modification.
*
* @example
* ```typescript
* class User {}
*
* expect(getClassName(User)).toBe('User');
* expect(getClassName(new User())).toBe('User');
* ```
*/
export declare function getClassName<T>(classTypeOrInstance: ClassType<T> | Object): string;
/**
* Same as getClassName but appends the propertyName.
*/
export declare function getClassPropertyName<T>(classType: ClassType<T> | Object, propertyName: string): string;
export declare function applyDefaults<T>(classType: ClassType<T>, target: {
[k: string]: any;
}): T;
/**
* Tries to identify the object by normalised result of Object.toString(obj).
*/
export declare function identifyType(obj: any): string;
/**
* Returns the ClassType for a given instance.
*/
export declare function getClassTypeFromInstance<T>(target: T): ClassType<T>;
/**
* Returns a human-readable string representation from the given value.
*/
export declare function stringifyValueWithType(value: any, depth?: number): string;
/**
* Changes the class of a given instance and returns the new object.
*
* @example
* ```typescript
*
* class Model1 {
* id: number = 0;
* }
*
* class Model2 {
* id: number = 0;
* }
*
* const model1 = new Model1();
* const model2 = changeClass(model1, Model2);
* model2 instanceof Model2; //true
* ```
*/
export declare function changeClass<T>(value: object, newClass: ClassType<T>): T;
export declare function prettyPrintObject(object: object, depth?: number): string;
export declare function indexOf<T>(array: T[], item: T): number;
export declare function sleep(seconds: number): Promise<void>;
/**
* Creates a shallow copy of given array.
*/
export declare function copy<T>(v: T[]): T[];
/**
* Checks whether given array or object is empty (no keys). If given object is falsy, returns false.
*/
export declare function empty<T>(value?: T[] | object | {}): boolean;
/**
* Returns the size of given array or object.
*/
export declare function size<T>(array: T[] | {
[key: string]: T;
}): number;
/**
* Returns the first key of a given object.
*/
export declare function firstKey(v: {
[key: string]: any;
} | object): string | undefined;
/**
* Returns the last key of a given object.
*/
export declare function lastKey(v: {
[key: string]: any;
} | object): string | undefined;
/**
* Returns the first value of given array or object.
*/
export declare function first<T>(v: {
[key: string]: T;
} | T[]): T | undefined;
/**
* Returns the last value of given array or object.
*/
export declare function last<T>(v: {
[key: string]: T;
} | T[]): T | undefined;
/**
* Returns the average of a number array.
*/
export declare function average(array: number[]): number;
export declare function prependObjectKeys(o: {
[k: string]: any;
}, prependText: string): {
[k: string]: any;
};
export declare function appendObject(origin: {
[k: string]: any;
}, extend: {
[k: string]: any;
}, prependKeyName?: string): void;
/**
* A better alternative to "new Promise()" that supports error handling and maintains the stack trace for Error.stack.
*
* When you use `new Promise()` you need to wrap your code inside a try-catch to call `reject` on error.
* asyncOperation() does this automatically.
*
* When you use `new Promise()` you will lose the stack trace when `reject(new Error())` is called.
* asyncOperation() makes sure the error stack trace is the correct one.
*
* @example
* ```typescript
* await asyncOperation(async (resolve, reject) => {
* await doSomething(); //if this fails, reject() will automatically be called
* stream.on('data', (data) => {
* resolve(data); //at some point you MUST call resolve(data)
* });
* });
* ```
*
* @reflection never
*/
export declare function asyncOperation<T>(executor: (resolve: (value: T) => void, reject: (error: any) => void) => void | Promise<void>): Promise<T>;
/**
* When an API is called that returns a promise that loses the stack trace on error, you can use fixAsyncOperation().
*
* ```typescript
* cons storage = new BrokenPromiseStorage();
* const files = await fixAsyncOperation(storage.files('/'));
* ```
*/
export declare function fixAsyncOperation<T>(promise: Promise<T>): Promise<T>;
export declare function mergePromiseStack<T>(promise: Promise<T>, stack?: string): Promise<T>;
/**
* @beta
*/
export declare function createStack(removeCallee?: boolean): string;
/**
* @beta
*/
export declare function mergeStack(error: Error, stack: string): void;
/**
* Makes sure the given value is an error. If it's not an error, it creates a new error with the given value as message.
*/
export declare function ensureError(error?: any, classType?: ClassType): Error;
export declare function collectForMicrotask<T>(callback: (args: T[]) => void): (arg: T) => void;
export declare function getPathValue(bag: {
[field: string]: any;
}, parameterPath: string, defaultValue?: any): any;
export declare function setPathValue(bag: object, parameterPath: string, value: any): void;
export declare function deletePathValue(bag: object, parameterPath: string): void;
/**
* Returns the human-readable byte representation.
*/
export declare function humanBytes(bytes: number, si?: boolean): string;
/**
* Returns the number of properties on `obj`. This is 20x faster than Object.keys(obj).length.
*/
export declare function getObjectKeysSize(obj: object): number;
export declare function getParentClass(classType: ClassType): ClassType | undefined;
export declare function getInheritanceChain(classType: ClassType): ClassType[];
export declare function inDebugMode(): boolean;
/**
* Create a new class with the given name.
* This is currently the only know way to make it workable in browsers too.
*/
export declare function createDynamicClass(name: string, base?: ClassType): ClassType;
export declare function iterableSize(value: Array<unknown> | Set<unknown> | Map<unknown, unknown>): number;
/**
* Returns __filename, works in both cjs and esm.
*/
export declare function getCurrentFileName(offset?: number): string;
/**
* Returns the directory name of the current file (__dirname), works in both cjs and esm.
*/
export declare function getCurrentDirName(): string;
/**
* Escape special characters in a regex string, so it can be used as a literal string.
*/
export declare function escapeRegExp(string: string): string;
export declare function hasProperty(object: any, property: any): boolean;
/**
* Returns an iterator of numbers from start (inclusive) to stop (exclusive) by step.
*/
export declare function range(startOrLength: number, stop?: number, step?: number): IterableIterator<number>;
/**
* Returns an array of numbers from start (inclusive) to stop (exclusive) by step.
*
* Works the same as python's range function.
*/
export declare function rangeArray(startOrLength: number, stop?: number, step?: number): number[];
/**
* Returns a combined array of the given arrays.
*
* Works the same as python's zip function.
*/
export declare function zip<T extends (readonly unknown[])[]>(...args: T): {
[K in keyof T]: T[K] extends (infer V)[] ? V : never;
}[];
/**
* Forwards the runtime type arguments from function x to function y.
* This is necessary when a generic function is overridden and forwarded to something else.
*
* ```typescript
* let generic = <T>(type?: ReceiveType<T>) => undefined;
*
* let forwarded<T> = () => {
* forwardTypeArguments(forwarded, generic); //all type arguments are forwarded to generic()
* generic(); //call as usual
* }
*
* forwarded<any>(); //generic receives any in runtime.
* ```
*
* Note that generic.bind(this) will not work, as bind() creates a new function and forwarded type arguments can not
* reach the original function anymore.
*
* ```typescript
* let forwarded<T> = () => {
* const bound = generic.bind(this);
* forwardTypeArguments(forwarded, bound); //can not be forwarded anymore
* bound(); //fails
* }
* ```
*
* This is a limitation of JavaScript. In this case you have to manually forward type arguments.
*
* ```typescript
* let forwarded<T> = (type?: ReceiveType<T>) => {
* const bound = generic.bind(this);
* bound(type);
* }
* ```
*/
export declare function forwardTypeArguments(x: any, y: any): void;
export declare function formatError(error: any, withStack?: boolean): string;
/**
* Asserts that the given object is an instance of the given class.
*/
export declare function assertInstanceOf<T>(object: any, constructor: {
new (...args: any[]): T;
}): asserts object is T;
/**
* Asserts that the given value is defined (not null and not undefined).
*/
export declare function assertDefined<T>(value: T): asserts value is NonNullable<T>;
export declare type __ΩCustomError = any[];
export declare type __ΩClassType = any[];
export declare type __ΩAbstractClassType = any[];
export declare type __ΩExtractClassType = any[];