Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the type of an object is a class?

Tags:

typescript

I'm trying to check if the type of an object is a class, any class at all.

This is what I've tried:

export type IsClass<T> = (
    T extends ({new (...args: any[]): any}) ? true : false
)
class SomeClass {}
const a: IsClass<number> = false;
const b: IsClass<SomeClass> = false;
const c: IsClass<({new(): any})> = true;

Last I checked, it was not possible to tell if a type was an object or a class, but I couldn't find the Typescript issue pertaining to it.

How can I check if the type of an object is a class?


Bonus: this is how to check it with actual code. It doesn't translate to type logic.

function isClass(target: any) {
  return typeof target === "object" && (/^(object|array)$/i.test(target.constructor.name) === false)
}

From what I can tell, Typescript knows the difference between an object and a class... sort of:

const a = {};
class B{};
const testA = new a();  //error: This expression is not constructable.
const testB = new B();

But I guess it can't tell that testB is a class object.

like image 481
Seph Reed Avatar asked Dec 06 '25 17:12

Seph Reed


1 Answers

Typescript has two separate namespaces. One for code and one for types. There is no way no classes at the code level. Types are only analyzed at compile time. This is because Typescript is a superset of Javascript. So there are no things like for example in Java, where you have a reflection API to check type structure.

What is your root problem? What are you aiming to achieve?

like image 179
Ville Venäläinen Avatar answered Dec 08 '25 09:12

Ville Venäläinen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!