有人知道TypeScript中String和String的区别吗?我假设它们应该是一样的,对吗?
var a: String = "test";
var b: string = "another test";
a = b;
b = a; // this gives a compiler error!
当前版本的编译器说:
Type 'String' is not assignable to type 'string'.
'string' is a primitive, but 'String' is a wrapper object.
Prefer using 'string' when possible.
那是虫子吗?
在JavaScript中,字符串既可以是字符串基本类型,也可以是字符串对象。下面的代码显示了两者的区别:
var a: string = 'test'; // string literal
var b: String = new String('another test'); // string wrapper object
console.log(typeof a); // string
console.log(typeof b); // object
你的错误:
类型'String'不能赋值给类型'String'。'string'是a
但'String'是一个包装器对象。
尽可能使用'string'。
由TS编译器抛出,因为您试图将类型字符串分配给字符串对象类型(通过new关键字创建)。编译器告诉你,你应该只对字符串基本类型使用类型string,你不能用这个类型来描述字符串对象类型。
这两种类型在JavaScript和TypeScript中是截然不同的——TypeScript只是提供了注释和检查类型的语法。
String引用具有String的对象实例。原型链中的原型。你可以通过多种方式获得这样的实例,例如new String('foo')和Object('foo')。你可以用instanceof操作符来测试String类型的实例,例如myString instanceof String。
字符串是JavaScript的基本类型之一,字符串值主要是用文字创建的。'foo'和"bar",以及作为各种函数和操作符的结果类型。你可以使用typeof myString === 'string'来测试字符串类型。
The vast majority of the time, string is the type you should be using - almost all API interfaces that take or return strings will use it. All JS primitive types will be wrapped (boxed) with their corresponding object types when using them as objects, e.g. accessing properties or calling methods. Since String is currently declared as an interface rather than a class in TypeScript's core library, structural typing means that string is considered a subtype of String which is why your first line passes compilation type checks.
下面是一个例子,它显示了两者的区别,这将有助于解释。
var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string;
String是JavaScript的String类型,您可以使用它来创建新的字符串。没有人这样做,因为在JavaScript中文字被认为更好,所以上面例子中的s2创建了一个新的字符串,没有使用new关键字,也没有显式地使用string对象。
string是TypeScript的字符串类型,你可以用它来输入变量、参数和返回值。
额外的笔记……
目前(2013年2月)s1和s2都是有效的JavaScript。s3是有效的TypeScript。
字符串的使用。你可能永远不需要使用它,字符串字面量被普遍接受为初始化字符串的正确方式。在JavaScript中,使用对象字面值和数组字面值也被认为更好:
var arr = []; // not var arr = new Array();
var obj = {}; // not var obj = new Object();
如果你真的很喜欢字符串,你可以在TypeScript中以以下两种方式之一使用它……
var str: String = new String("Hello world"); // Uses the JavaScript String object
var str: string = String("Hello World"); // Uses the TypeScript string type