简体   繁体   English

需要帮助了解这些 TypeScript 声明有何不同

[英]Need help understanding how these TypeScript declarations are different

Trying to understand the differences between these declarations:试图了解这些声明之间的区别:

let foo = new String('bar'); // StringConstructor
let foo = new Number(100); // NumberConstructor

let foo: String = 'bar'; // interface
let foo: Number = 100; // interface

var foo: string = 'bar'; // globally scoped?
var foo: number = 100; // globally scoped?

Are there any particular pros and cons to using different declarations over others?使用不同的声明而不是其他声明有什么特别的优点和缺点吗?

JavaScript's primitive String is immutable, which is a huge difference between passing an object (created with new ), vs passing the primitive ( myVar = 'my-value'; ). JavaScript 的原始字符串是不可变的,这是传递 object(使用new创建)与传递原始字符串( myVar = 'my-value'; )之间的巨大差异。

For example, try something like:例如,尝试类似:

var myObject = new String('my value');
var myPrimitive = 'my value';

function myFunc(x) {
  x.mutation = 'my other value';
}

myFunc(myObject);
myFunc(myPrimitive);

console.log('myObject.mutation:', myObject.mutation);
console.log('myPrimitive.mutation:', myPrimitive.mutation);

Which should output: output应该是哪个:

myObject.mutation: my other value
myPrimitive.mutation: undefined

Note that the same applies to Number as well.请注意,这同样适用于Number

let/var are not related to Typescript, they are related to Javascript: let/var 与 Typescript 无关,它们与 Javascript 相关:

What's the difference between using "let" and "var"? 使用“let”和“var”有什么区别?

String created by calling "new String()" is typeof object and you should avoid it.通过调用“new String()”创建的字符串类型为 object,您应该避免使用它。

In second and third cases, "String" is Javascript object used for creating strings, "string" is typescript type which should be used for typing string variable.在第二种和第三种情况下,“String”是 Javascript object 用于创建字符串,“string”是 typescript 类型,应该用于键入字符串变量。

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

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