typescript 打字稿:字符串和字符串之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14727044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript: difference between String and string
提问by Paul0515
Does anyone know the difference between String and string in TypeScript? Am I correct in assuming that they ought to be the same?
有谁知道 TypeScript 中 String 和 string 的区别?我假设它们应该相同是否正确?
var a: String = "test";
var b: string = "another test";
a = b;
b = a; // this gives a compiler error!
Current version of the compiler says:
当前版本的编译器说:
Type 'String' is not assignable to type 'string'.
'string' is a primitive, but 'String' is a wrapper object.
Prefer using 'string' when possible.
Is that a bug?
这是一个错误吗?
采纳答案by Fenton
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
is the JavaScript String type, which you coulduse 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
是 JavaScript String 类型,您可以使用它来创建新字符串。没有人这样做,因为在 JavaScript 中文字被认为更好,因此s2
在上面的示例中,在不使用new
关键字和不显式使用String
对象的情况下创建了一个新字符串。
string
is the TypeScript string type, which you can use to type variables, parameters and return values.
string
是 TypeScript 字符串类型,可用于键入变量、参数和返回值。
Additional notes...
补充说明...
Currently (Feb 2013) Both s1
and s2
are valid JavaScript. s3
is valid TypeScript.
当前(2013 年 2 月)s1
和s2
都是有效的 JavaScript。s3
是有效的打字稿。
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:
的使用String
。您可能永远不需要使用它,字符串文字被普遍接受为初始化字符串的正确方法。在 JavaScript 中,也认为使用对象字面量和数组字面量更好:
var arr = []; // not var arr = new Array();
var obj = {}; // not var obj = new Object();
If you really had a penchant for the string, you could use it in TypeScript in one of two ways...
如果您真的很喜欢字符串,则可以通过以下两种方式之一在 TypeScript 中使用它……
var str: String = new String("Hello world"); // Uses the JavaScript String object
var str: string = String("Hello World"); // Uses the TypeScript string type
回答by Joe Lee-Moyet
The two types are distinct in JavaScript as well as TypeScript - TypeScript just gives us syntax to annotate and check types as we go along.
这两种类型在 JavaScript 和 TypeScript 中是不同的 - TypeScript 只是为我们提供了在我们进行时注释和检查类型的语法。
String
refers to an object instance that has String.prototype
in its prototype chain. You can get such an instance in various ways e.g. new String('foo')
and Object('foo')
. You can test for an instance of the String
type with the instanceof
operator, e.g. myString instanceof String
.
String
指的是String.prototype
在其原型链中具有的对象实例。您可以通过各种方式获得这样的实例,例如new String('foo')
和Object('foo')
。您可以String
使用instanceof
运算符测试该类型的实例,例如myString instanceof String
.
string
is one of JavaScript's primitive types, and string
values are primarily created with literals e.g. 'foo'
and "bar"
, and as the result type of various functions and operators. You can test for string
type using typeof myString === 'string'
.
string
是 JavaScript 的基本类型之一,string
值主要由字面量创建,例如'foo'
和"bar"
,并作为各种函数和运算符的结果类型。您可以string
使用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.
大多数情况下,string
是您应该使用的类型 - 几乎所有接受或返回字符串的 API 接口都会使用它。所有 JS 原始类型在用作对象时,例如访问属性或调用方法时,都会用它们对应的对象类型包装(装箱)。由于String
当前在TypeScript 的核心库中被声明为接口而不是类,结构类型意味着它string
被视为子类型,String
这就是为什么你的第一行通过编译类型检查。
回答by Willem van der Veen
In JavaScript strings can be either string primitive type or string objects. The following code shows the distinction:
在 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
Your error:
你的错误:
Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
类型 'String' 不可分配给类型 'string'。'string' 是一个原语,但 'String' 是一个包装对象。尽可能使用“字符串”。
Is thrown by the TS compiler because you tried to assign the type string
to a string object type (created via new
keyword). The compiler is telling you that you should use the type string
only for strings primitive types and you can't use this type to describe string object types.
由 TS 编译器抛出,因为您试图将类型分配给string
字符串对象类型(通过new
关键字创建)。编译器告诉您,您应该string
仅将类型用于字符串原始类型,而不能使用此类型来描述字符串对象类型。
回答by xgqfrms
TypeScript: String
vs string
打字稿:String
vsstring
Argument of type 'String' is not assignable to parameter of type 'string'.
'string' is a primitive, but 'String' is a wrapper object.
Prefer using 'string' when possible.
“String”类型的参数不能分配给“string”类型的参数。
'string' 是一个原语,但 'String' 是一个包装对象。
尽可能使用“字符串”。
demo
演示
String Object
字符串对象
// error
class SVGStorageUtils {
store: object;
constructor(store: object) {
this.store = store;
}
setData(key: String = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
getData(key: String = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
}
string primitive
字符串原语
// ok
class SVGStorageUtils {
store: object;
constructor(store: object) {
this.store = store;
}
setData(key: string = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
getData(key: string = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
}
回答by Javier Aviles
For quick readers:
对于快速读者:
Don'tever usethe types Number, String, Boolean, Symbol, or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.
永远不要使用类型 Number、String、Boolean、Symbol 或 Object 这些类型是指几乎从未在 JavaScript 代码中正确使用的非原始盒装对象。
source: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html
来源:https: //www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html