3

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.

ostrebler
  • 940
  • 9
  • 32

1 Answers1

7

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

Vojtěch Strnad
  • 2,420
  • 2
  • 10
  • 15