1

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.

gevik
  • 3,177
  • 4
  • 25
  • 28

2 Answers2

2

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
basarat
  • 261,912
  • 58
  • 460
  • 511
  • This looks like a cleaner solution. I have to run both through my unit tests and see the result. Thank you :) – gevik Apr 08 '16 at 00:08
1

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
Community
  • 1
  • 1
David Sherret
  • 101,669
  • 28
  • 188
  • 178