UNPKG

@dozerg/no-new

Version:

Convert ES6 class constructor to normal function.

35 lines (34 loc) 798 B
/** * Infer the function type of a class constructor. * * @example * ``` * class A { * constructor(a: numbber, b?: string) {} * } * * type F = CtorToFun<typeof A>; // expect (a: numbber, b?: string) => A. Please note 'new' is removed. * ``` */ type CtorToFun<T extends { new (...args: any[]): unknown; }> = T extends { new (...args: infer A): infer B; } ? (...args: A) => B : unknown; /** * Return a function to construct a class object without 'new'. * * @example * ``` * class A { * constructor(a: numbber, b: string) {} * } * * const AA = noNew(A); * const a = AA(1, 'abc'); // same as new A(1, 'abc'); * ``` */ export default function noNew<T extends { new (...args: any[]): unknown; }>(c: T): CtorToFun<T>; export {};