簡體   English   中英

需要幫助了解這些 TypeScript 聲明有何不同

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

試圖了解這些聲明之間的區別:

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?

使用不同的聲明而不是其他聲明有什么特別的優點和缺點嗎?

JavaScript 的原始字符串是不可變的,這是傳遞 object(使用new創建)與傳遞原始字符串( myVar = 'my-value'; )之間的巨大差異。

例如,嘗試類似:

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);

output應該是哪個:

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

請注意,這同樣適用於Number

let/var 與 Typescript 無關,它們與 Javascript 相關:

使用“let”和“var”有什么區別?

通過調用“new String()”創建的字符串類型為 object,您應該避免使用它。

在第二種和第三種情況下,“String”是 Javascript object 用於創建字符串,“string”是 typescript 類型,應該用於鍵入字符串變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM