简体   繁体   English

Node.js变量静态类型如何工作

[英]How does nodejs variable static typing work

I sometimes see Node code with variable types declared, such as: 我有时会看到带有声明的变量类型的Node代码,例如:

const st: string = "hello world";

What version of node supports this? 哪个版本的节点支持此功能? Where can I find the documentation on this (this is "static typing" right?)? 在哪里可以找到相关文档(这是“静态类型”吗?)? Can I use this in method variables? 我可以在方法变量中使用它吗?

That's not JavaScript, it's TypeScript ; 那不是JavaScript,它是TypeScript see the link for documentation. 请参阅文档链接。 TypeScript is basically JavaScript with a type system overlaid on it. TypeScript基本上是JavaScript,上面覆盖有类型系统。 It's then compiled to JavaScript by the TypeScript compiler. 然后由TypeScript编译器将其编译为JavaScript。 (The compiler also tends to support new JavaScript features before they're natively supported in JavaScript engines like the one in V8. For instance, TypeScript's compiler currently supports public class fields , which aren't in a JavaScript spec yet but are likely to be at some stage.) (在JavaScript引擎(如V8中的)原生支持之前,编译器还倾向于支持新的JavaScript功能。例如,TypeScript的编译器当前支持public class字段 ,该字段不在JavaScript规范中,但很可能是在某个阶段。)

Can I use this in method variables? 我可以在方法变量中使用它吗?

Yes, absolutely: 是的,一点没错:

function foo() : void {
    let a : number = 42;
    let q : string = "Life, the Universe, and Everything";

    // ...
}

If you tried to assign "glarb" to a , the TypeScript compiler would give you an error because a is declared as number . 如果你想分配"glarb"a ,因为打字稿编译器会给你一个错误a被声明为number Similarly, trying to return something from the function would raise an error because the function is declared to have a void return type (doesn't return anything). 同样,尝试从该函数返回某些内容会引发错误,因为该函数被声明为具有void返回类型(不返回任何内容)。

That compiles to: 编译为:

function foo() {
    var a = 42;
    var q = "Life, the Universe, and Everything";
    // ...
}

...which can run in any JavaScript environment. ...可以在任何JavaScript环境中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM