String 和 string 类型有什么区别? [英] What is the difference between types String and string?

查看:38
本文介绍了String 和 string 类型有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道 TypeScript 中 String 和 string 的区别吗?我假设它们应该相同是否正确?

Does anyone know the difference between String and string in TypeScript? Am I correct in assuming that they ought to be the same?

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.

这是一个错误吗?

推荐答案

这是一个显示差异的示例,有助于解释.

Here is an example that shows the differences, which will help with the explanation.

var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string;

String 是 JavaScript 字符串类型,您可以使用它来创建新字符串.没有人这样做,因为在 JavaScript 中,文字被认为更好,因此上面示例中的 s2 创建一个新字符串,而不使用 new 关键字,也没有明确使用 String 对象.

String is the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, so s2 in the example above creates a new string without the use of the new keyword and without explicitly using the String object.

string 是 TypeScript 字符串类型,您可以使用它来键入变量、参数和返回值.

string is the TypeScript string type, which you can use to type variables, parameters and return values.

附加说明...

目前(2013 年 2 月)s1s2 都是有效的 JavaScript.s3 是有效的 TypeScript.

Currently (Feb 2013) Both s1 and s2 are valid JavaScript. s3 is valid TypeScript.

String 的使用.您可能永远不需要使用它,字符串文字被普遍接受为初始化字符串的正确方法.在 JavaScript 中,也认为使用对象字面量和数组字面量更好:

Use of String. You probably never need to use it, string literals are universally accepted as being the correct way to initialise a string. In JavaScript, it is also considered better to use object literals and array literals too:

var arr = []; // not var arr = new Array();
var obj = {}; // not var obj = new Object();

如果您真的很喜欢字符串,您可以通过以下两种方式之一在 TypeScript 中使用它...

If you really had a penchant for the string, you could use it in TypeScript in one of two ways...

var str: String = new String("Hello world"); // Uses the JavaScript String object
var str: string = String("Hello World"); // Uses the TypeScript string type

这篇关于String 和 string 类型有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆