Conditional types by ahejlsberg · Pull Request #21316 · microsoft/TypeScript (original) (raw)

Sorry if there is a more appropriate place to post this, but thanks for the new (albeit sometimes complicated) ways to express behavior!

type IsValidArg = T extends object ? keyof T extends never ? false : true : true;

type NumberOfArgs = T extends (a: infer A, b: infer B, c: infer C, d: infer D, e: infer E, f: infer F, g: infer G, h: infer H, i: infer I, j: infer J) => any ? ( IsValidArg extends true ? 10 : IsValidArg extends true ? 9 : IsValidArg extends true ? 8 : IsValidArg extends true ? 7 : IsValidArg extends true ? 6 : IsValidArg extends true ? 5 : IsValidArg extends true ? 4 : IsValidArg extends true ? 3 : IsValidArg extends true ? 2 : IsValidArg extends true ? 1 : 0 ) : 0;

function numArgs(fn: T): NumberOfArgs { return fn.length as any; }

declare function exampleFunction(a: number, b: string, c?: any[]): void; const test = numArgs(exampleFunction);

screenshot


type Promisified = T extends (...args: any[]) => Promise ? T : ( T extends (a: infer A, b: infer B, c: infer C, d: infer D, e: infer E, f: infer F, g: infer G, h: infer H, i: infer I, j: infer J) => infer R ? ( IsValidArg extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J) => Promise : IsValidArg extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I) => Promise : IsValidArg extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H) => Promise : IsValidArg extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => Promise : IsValidArg extends true ? (a: A, b: B, c: C, d: D, e: E, f: F) => Promise : IsValidArg extends true ? (a: A, b: B, c: C, d: D, e: E) => Promise : IsValidArg extends true ? (a: A, b: B, c: C, d: D) => Promise : IsValidArg extends true ? (a: A, b: B, c: C) => Promise : IsValidArg extends true ? (a: A, b: B) => Promise : IsValidArg extends true ? (a: A) => Promise : () => Promise ) : never );

declare function promisify(fn: T): Promisified;

declare function exampleFunction2(a: number, b: string, c?: any[]): RegExp;

const test2 = promisify(exampleFunction2);

screenshot