字符串不是字符串

时间:2013-03-13 04:34:41

标签: typescript

将字符串视为字符串有效。然而,将String视为字符串被破坏了:

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

这是一个已知的编译器错误吗?

2 个答案:

答案 0 :(得分:5)

String是Javascript类型,而string是Typescript类型。我认为这不是一个奇怪的错误。主要是因为绝对没有理由使用String()构造函数而不是字符串文字。

见这里:Typescript: difference between String and string

答案 1 :(得分: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.

你几乎从不想要一个对象字符串,因为它的怪癖(例如,一个空的对象字符串是真的),所以你几乎总是想要new String,而不是String。没有String的{​​{1}}甚至可以将对象字符串转换回原始字符串:

new

我不知道这个问题是否在TypeScript中出现,但原始/对象的区别,特别是真实性问题在typeof String(new String("Hi! I'm a string!")) // => "string" 变得非常奇怪。例如:

Boolean

简而言之,这是因为对象/原语的区别。你几乎总是想要你可以选择的原语。