Typedef in javascript

This is not a feature of pure JavaScript, but it can be done if you're using Google's Closure Compiler, which allows you to precompile your JavaScript and check the types at compile time.

So you could have

/** @type {string} */
var str = "Lorem ipsum";

And if str were not a string, you'd get a warning when you compile your code.

See https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler for more information.


You can not override or define keywords in javascript.

So, No, it can't be done.

Regarding to your example, as @Lightness Races in Orbit commented, the example does not make sense as you don't have static typing in javascript(unlike java, C# etc')!

var x = "12";
x = 12;
x = true;
x = function (){/*.../*};

All valid!

so let's say you could define string to be var, will this make sense to you:

string x = "12";
x = 12;
x = true;
x = function (){/*.../*};

There will be no errors, but ?!


No, this is not possible. Period.

Your example is also an impossible thing to want, even though I understand the motivation. JavaScript is dynamically typed. You cannot declare variables to be string. And in that light the whole statement string x = "foo"; is pointless.

EDIT Yes, it's possible to achieve this effect with TypeScript. No, TypeScript is not JavaScript. The question was about the latter. That you can do a similar thing in a completely different programming language does not make this answer incorrect or obsolete.

Declaring a variable as, e.g., string will remain impossible in JavaScript until the day when the ECMAScript Standard adds static typing to the language.

Tags:

Javascript