type IsFirstTrue<T extends unknown[]> =
T extends [infer First, ...infer Rest]
? First extends true
? true
: false
: false
// let a: boolean
let a: IsIndexedTypeTrue<[boolean]>
I'm trying to create a type IsFirstTrue that checks whether the first element of an array type is of type true.
For the type [boolean] as input the resulting type should evaluate to false since its first type is not of type true, but it evaluates to boolean instead, which is odd since in the code the boolean type is not even stated, only true or false. Why does this happen?
CodePudding user response:
Note that boolean is neither true nor false (it is a representation of a union of both):
declare const b: true | false;
//^? const b: boolean
I think you're probably looking for something like this:
type IsFirstTrue<T extends readonly unknown[]> =
T extends [true, ...readonly unknown[]]
? true
: false;
declare const a: IsFirstTrue<[boolean]>;
//^? const a: false
declare const b: IsFirstTrue<[true]>;
//^? const b: true
declare const c: IsFirstTrue<[false]>;
//^? const c: false
declare const d: IsFirstTrue<[string]>;
//^? const d: false
declare const e: IsFirstTrue<[number]>;
//^? const e: false
declare const f: IsFirstTrue<[true, number]>;
//^? const f: true
// ...etc.
