Add an IfElse type to make a nested or long ternary expression more concise, clear, easier to write, and also maintain. Here is an implementation and example of how it would work, and there could also be other generic types that return true or false.
type Extends<T, K> = [T] extends [K] ? true : false;
type HasKey<T, K extends string> = K extends keyof T ? true : false;
type HasIndex<T, K extends number | `${number}`> = HasKey<T, `${K}`>;
type And<T extends boolean[]> = (
T extends [infer Item, ...infer Rest] ?
Item extends true ?
Rest[number] extends never ?
true
: Rest extends Array<boolean> ?
And<Rest>
: never
: false
: never
);
type Or<T extends boolean[]> = (
T extends [infer Item, ...infer Rest] ?
Item extends false ?
Rest[number] extends never ?
false
: Rest extends Array<boolean> ?
Or<Rest>
: never
: true
: never
);
type Not<T extends boolean> = T extends true ? false : true;
type GetProp<T, K extends string> = K extends keyof T ? T[K] : never;
type GetIndex<T, K extends number | `${number}`> = GetProp<T, `${K}`>;
type Block = [boolean, any];
type IfElse<T extends Array<Block>, Else = never> = (
T extends [infer Item, ...infer Rest] ?
GetProp<Item, "0"> extends true ?
GetProp<Item, "1">
: Rest extends Array<Block> ?
IfElse<Rest, Else>
: never
: Else
);
type Test<T> = IfElse<[
[Extends<T, string>, "string"],
[Extends<T, number>, "number"],
[Extends<T, boolean>, "boolean"],
[Extends<T, null>, "null"],
[Extends<T, any[]>, "array"],
], "object">;
type test1 = Test<"">; // type is "string"
type test2 = Test<string>; // type is "string"
type test3 = Test<0>; // type is "number"
type test4 = Test<number>; // type is "number"
type test5 = Test<null>; // type is "null"
type test6 = Test<[0, number, string, ""]>; // type is "array"
type test7 = Test<object>; // type is "object"
type test8 = Test<{ age: number; name: string; }>; // type is "object"
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too