Is there a mechanism to type JavaScript vars, so can determine the data type that is returned by an assignment? As JavaScript is a dynamic language this is not possible ?
-
You can use TypeScript which is a superset of JavaScript that transpiles down to JavaScript. See: http://www.typescriptlang.org/ Got a feeling it will be more in usage now since Angular 2 will be using it. – Jimmy Chandra May 09 '15 at 09:19
-
possible duplicate of [How do I get the name of an object's type in JavaScript?](http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript) – Markus May 09 '15 at 09:37
2 Answers
JavaScript variables can hold many data types: numbers, strings, arrays, objects
We can find out the type of a variable using typeof
.
if(typeof myvar === 'number') {
// code you want
}
or you can use Object.prototype.toString
so you won't have to identify the difference between objects & primitive types
> Object.prototype.toString.call(80)
"[object Number]"
> Object.prototype.toString.call("samouray")
"[object String]"
hope this was helpful.

- 66,517
- 15
- 143
- 132

- 578
- 1
- 11
- 26
You could use a precompiler to add types (and other features) at development time using e.g. TypeScript:
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
var greeter : Greeter = new Greeter("world");
TypeScript is a super set of JavaScript (meaning you can use your existing JavaScript code as is and pass it to the TypeScript compiler) and was developed to provide developers with type safety, simpler inheritance etc. It compiles to plain JavaScript.
To get a first impression you can play with the compiler for a first hands on experience.
Get the actual type at runtime
Since TypeScript compiles to plain JavaScript one cannot use typeof
to get the name of type declared in TypeScript (this would return e.g. object for the Greeter defined above). To work around this, something like the following JavaScript method is required:
function getClassName(obj) {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec(obj["constructor"].toString());
return (results && results.length > 1) ? results[1] : "";
}
For more information refer to How do I get the name of an object's type in JavaScript? where I found the snippet above.