运算符“+”不能应用于 TypeScript 中的“String”和“String”类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31303784/
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
Operator '+' cannot be applied to types 'String' and 'String' in TypeScript
提问by Engr. Hasanuzzaman Sumon
I am new to TypeScript trying to play with it. But I face a wired problem. When I try to concatenate two String
type using +
operator it's give an error that is
我是 TypeScript 的新手,正在尝试使用它。但我面临一个有线问题。当我尝试String
使用+
运算符连接两种类型时,它给出了一个错误
Operator '+' cannot be applied to types 'String' and 'String'
运算符 '+' 不能应用于类型 'String' 和 'String'
My Code snap is
我的代码快照是
var firstName: String = 'Foo';
var lastName: String = 'Bar';
var name = firstName + lastName;
If I use string
instead String
or add extra ''
it works fine. I checked, within JavaScript we can use +
on two String
object then why it's show error in TypeScript ? Is it bug or feature ? I definitely missing something. Detail explanation appreciated.
如果我string
改用 String
或添加额外的''
它工作正常。我检查过,在 JavaScript 中我们可以+
在两个String
对象上使用,那么为什么它在 TypeScript 中显示错误?它是错误还是功能?我肯定错过了一些东西。详细解释表示赞赏。
回答by Ryan Cavanaugh
String
is not the same as string
. Always use string
unless you really, really know what you're up to.
String
不一样string
。string
除非您真的非常清楚自己在做什么,否则请始终使用。
The upper-case name String
refers to the boxed version of a primitive string. These should generally be avoided wherever possible -- they don't behave like normal string
s in subtle and unexpected ways (for example typeof new String('hello')
is "object"
, not "string"
).
大写名称String
指的是原始字符串的装箱版本。这些通常应该尽可能避免——它们不会以string
微妙和意外的方式表现得像普通s(例如typeof new String('hello')
is "object"
, not "string"
)。