gevik
gevik

Reputation: 3407

How to distinguish between a class and function

Is there a way to distinguish between a class (not its instance!) and a function in TypeScript during runtime.

Normally classes in typescript are transpiled to javascript functions and during runtime I could not find a nice way to check whether an identifier is a function or a class type!

For example:

function func1() {
	
}

class class1 {
	
}

// ugly hack
(<any>class1.prototype).isclass = true;

// ugly hack test
function is_class(clazz:any) {
	return (
		clazz 
		&& clazz.prototype 
		&& (<any>clazz.prototype).isclass === true
	);
}

console.log(typeof(func1) === 'function'); // returns true !!
console.log(typeof(class1) === 'function'); // returns true !!

console.log(is_class(func1)); // returns false :)
console.log(is_class(class1)); // returns true :)

Any ideas for a better solution? Thanks.

Upvotes: 1

Views: 580

Answers (2)

basarat
basarat

Reputation: 275957

You cannot do it definitively but you can use a heuristic, as class methods generally go on prototype so:

class Foo {
   foo(){}
} 
function foo(){}
console.log(!!Object.keys(Foo.prototype).length); // true : is class 
console.log(!!Object.keys(foo.prototype).length); // false : is not a class

Upvotes: 2

David Sherret
David Sherret

Reputation: 106660

No, not when targeting ES5 or below. Classes are functions as can be seen in the compiled JavaScript:

var class1 = (function () {
    function class1() {
    }
    return class1;
}());

However, if you are targeting ES6 then you can tell. Take a look at this answer.

That said, you can create a class that all other classes inherit from:

class BaseClass {
    static isClass = true;
}

class Class1 extends BaseClass {

}

console.log(Class1.isClass); // true

Upvotes: 1

Related Questions