Typedef in javascript

Is there any way to introduce typedef in javascript? Maybe getting it from a prototype object or something else?

For example, I would like to type the var keyword.

 var string = prototype.var; 

So, instead of using "var", I can use:

 string blaat = "It like using the 'var' keyword"; 

Is this possible somehow in javascript?

+6
source share
3 answers

No, It is Immpossible. Period.

Your example is also an impossible thing, although I understand the motivation. JavaScript is dynamically typed. You cannot declare variables as string. And in this light, the whole instruction is string x = "foo"; pointless.

EDIT Yes, this effect can be achieved using TypeScript. No, TypeScript is not JavaScript. The question was about the last. Just because you can do this in a completely different programming language does not make this answer incorrect or obsolete.

Declaring a variable, such as string , in JavaScript will not be possible until the day the ECMAScript standard adds static typing to the language.

+8
source

You cannot override or define keywords in javascript.

So no, this is impossible to do.

As for your example, as @Lightness Races in Orbit commented , this example does not make sense, since you don't have static typing in javascript (unlike java , C# , etc.)!

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

All acting!

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

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

There will be no errors, but ?!

+7
source

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

So you may have

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

And if str not a string, you will get a warning when compiling the code.

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

-1
source

Source: https://habr.com/ru/post/1402011/


All Articles