将字符串视为字符串是可行的。然而,将字符串视为字符串是不正确的:
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
这是一个已知的编译器错误吗?
发布于 2013-03-13 12:58:27
String是Javascript类型,而string是Typescript类型。与其说这是一个bug,不如说是一种怪癖。主要是因为绝对没有理由使用String()构造函数而不是字符串文字。
发布于 2013-03-13 13:05:28
这源于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.你几乎从来不想要一个对象字符串,因为它的怪癖(例如,空的对象字符串是真实的),所以你几乎总是想要String而不是使用new String。没有new的String甚至可以将对象字符串转换回原始字符串:
typeof String(new String("Hi! I'm a string!")) // => "string"我不知道这个问题是否会在TypeScript中出现,但在Boolean中,原语/对象的区别,特别是真实性问题变得非常奇怪。例如:
var condition = new Boolean(false);
if(condition) { // always true; objects are always truthy
alert("The world is ending!");
}简而言之,这是因为对象/原语的区别。你几乎总是想要基本类型,在你可以选择的地方。
https://stackoverflow.com/questions/15377159
复制相似问题