2013-03-13 125 views
2

將字符串看作字符串的工作原理。然而思維字符串作爲字符串被打破:字符串不是字符串

var str1:String = "asdf"; 
var str2:String = new String("asdf"); 
var str3:string = "asdf"; 
var str4:string = new String("asdf"); // Error 

Try It

另外:

var interfaceBased:String = "123"; 
var keywordBased:string ="123"; 
interfaceBased=keywordBased; 
keywordBased=interfaceBased; // Error 

Try It

這是一個已知的編譯器錯誤?

+0

http://typescript.codeplex.com/workitem/810 – basarat 2013-03-13 04:57:22

+1

可能重複[Typescript:字符串和字符串之間的區別](http://stackoverflow.com/questions/14727044/typescript-difference-between-string -and弦) – JcFx 2013-03-13 07:46:42

回答

3

這從一個JavaScript怪癖莖:有原始的字符串和對象的字符串。一個原始的字符串,那麼,你每天的字符串:

typeof "Hi! I'm a string!" // => "string" 

但是,使用new任何時候,您創建一個對象,而不是原始的:

typeof new String("Hi! I'm a string!") // => "object" 

的JavaScript也隱含地創建一個對象串出每當你訪問一個屬性時,因爲只有對象可以有屬性:

var s = "Hi! I'm a string!"; 
s.property = 6; // s implicitly coerced to object string, property added 
console.log(s.property); // => undefined 
// property was added to the object string, but then the object string was 
// discarded as s still contained the primitive string. then s was coerced again 
// and the property was missing as it was only added to an object whose reference 
// was immediately dropped. 

你幾乎從不想要一個對象字符串,因爲它的怪癖(例如,空的對象字符串是truthy),所以您幾乎總是需要String,而不是使用new StringString沒有new甚至可以轉換一個對象的字符串返回到原始的字符串:

typeof String(new String("Hi! I'm a string!")) // => "string" 

我不知道,如果在打字稿這個問題的表面,但原始/對象的區別,特別是感實性問題變得非常奇怪與Boolean 。例如:

var condition = new Boolean(false); 
if(condition) { // always true; objects are always truthy 
    alert("The world is ending!"); 
} 

總之,這是因爲對象/原始的區別。你幾乎總是希望有原始選擇的地方。

相關問題