Check if type is the unknown type

Viewed 292

Is there a way to check if a type parameter T is in fact the unknown type ?

I know it can be done to check for any (solution here), but was wondering about unknown.

1 Answers

The simplest solution is this:

type IsUnknown<T> = unknown extends T ? true : never

However, it also returns true for any, since that is assignable to any type. If you need to handle that case, borrow the solution for IsAny and do this:

type IsUnknown<T> = IsAny<T> extends true ? never : unknown extends T ? true : never

type A = IsUnknown<unknown> // true
type B = IsUnknown<any> // never
type C = IsUnknown<never> // never
type D = IsUnknown<string> // never

Playground link

Related