TrevTheDev
TrevTheDev

Reputation: 2737

Test if a type is any[] or unknown[]

How does one test if a type is strictly unknown[] or any[]?

Related, but not relevant, these are how I'm testing for other types:

type IsStrictAny<T> = 0 extends (1 & T) ? T : never;
type IsNotStrictAny<T> = T extends IsStrictAny<T> ? never : T
type IsVoid<T> = T extends void ? T : never
type IsStrictVoid<T> = IsVoid<T> & IsNotStrictAny<T>
type IsStrictNever<T> = [T] extends [never] ? true : false
type IsStrictUnknown<T> = T extends IsStrictAny<T> ? never : unknown extends T ? T : never

If there are better ways to do this then that would also be appreciated.

Upvotes: 1

Views: 170

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

Why not extract the item using a conditional type and then use the IsStrictAny you already use to detect any

type IsStrictAnyArray<T> = T extends Array<infer U> ? IsStrictAny<U> : never;

// any
type T1 = IsStrictAnyArray<any[]>
// All are never
type T2 = IsStrictAnyArray<unknown[]>
type T3 = IsStrictAnyArray<void[]>
type T4 = IsStrictAnyArray<undefined[]>
type T5 = IsStrictAnyArray<null[]>
type T6 = IsStrictAnyArray<number[]>
type T7 = IsStrictAnyArray<any>
type T8 = IsStrictAnyArray<never>
type T9 = IsStrictAnyArray<unknown>

Playground Link

You can also detect tuples if you check the length property.


type IsNotTuple<T> = T extends Array<any> ? number extends T['length'] ? T: never : never;
// Tuple detection 
// any
type T10 = IsStrictAnyArray<IsNotTuple<any[]>>
// never
type T11 = IsStrictAnyArray<IsNotTuple<[any]>>

Playground Link

Upvotes: 1

Related Questions