运算符“+”不能应用于 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:02:28  来源:igfitidea点击:

Operator '+' cannot be applied to types 'String' and 'String' in TypeScript

javascripttypescript

提问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 Stringtype 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 stringinstead Stringor add extra ''it works fine. I checked, within JavaScript we can use +on two Stringobject 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

Stringis not the same as string. Always use stringunless you really, really know what you're up to.

String不一样stringstring除非您真的非常清楚自己在做什么,否则请始终使用。

The upper-case name Stringrefers to the boxed version of a primitive string. These should generally be avoided wherever possible -- they don't behave like normal strings 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")。