1

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 ?

2

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.