Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript check for the 'any' type

Tags:

typescript

Is it possible to check for the exact any type using typescript conditionals?

type IsAny<T> = T extends any ? true : never

type A = IsAny<any> // true
type B = IsAny<number> // never
type C = IsAny<unknown> // never
type D = IsAny<never> // never
like image 866
Sam Denty Avatar asked Apr 05 '19 18:04

Sam Denty


People also ask

How do you check if a variable is type string in TypeScript?

Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.

What type is this in TypeScript?

In TypeScript, we can use this as a type. It represents the subtype of the containing class or interface. We can use it to create fluent interfaces easily since we know that each method in the class will be returning the instance of a class.

How do I check my TypeScript Instanceof?

Use the instanceof operator to check if an object is an instance of a class, e.g. if (myObj instanceof MyClass) {} . The instanceof operator checks if the prototype property of the constructor appears in the prototype chain of the object and returns true if it does.


2 Answers

Yeah, you can test for any:

type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N; 
type IsAny<T> = IfAny<T, true, never>;
type A = IsAny<any> // true
type B = IsAny<number> // never
type C = IsAny<unknown> // never
type D = IsAny<never> // never

The explanation for this is in this answer. In short, any is intentionally unsound, and violates the normal rules of types. You can detect this violation because it lets you do something crazy like assign 0 to 1.

like image 191
jcalz Avatar answered Oct 02 '22 18:10

jcalz


another way to detect IsAny:

type IsAny<T> = (
  unknown extends T
    ? [keyof T] extends [never] ? false : true
    : false
);

result of IsAny with some values

like image 35
eczn Avatar answered Oct 02 '22 19:10

eczn