Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript String()和new String()可能具有相同的类型注释';字符串';_Typescript - Fatal编程技术网

Typescript String()和new String()可能具有相同的类型注释';字符串';

Typescript String()和new String()可能具有相同的类型注释';字符串';,typescript,Typescript,String('str')不是类型String的实例: // false String('str') instanceof String // true typeof String('str') === 'string' newstring('str')将在'str'周围创建一个包装器对象,从而导致: // true new String('str) instanceof String // false typeof new String('str') === 'string' 对我来说

String('str')
不是类型
String
的实例:

// false
String('str') instanceof String

// true
typeof String('str') === 'string'
newstring('str')
将在
'str'
周围创建一个包装器对象,从而导致:

// true
new String('str) instanceof String

// false
typeof new String('str') === 'string'
对我来说,这意味着

const myString: String = String('str')
应生成编译错误,因为类型无效,但不会。鉴于:

const myString: String = new String('str')
也不会生成编译错误。这也适用于其他基本包装器对象


这是故意的吗?若然,原因为何?如果我想区分
new String()
String()
,我做不到,这应该只是为了编译时的类型安全,但在运行时也可以使用
reflect metadata
,还是我遗漏了什么?

我很好奇您使用包装器对象的用例是什么。。。?我很少看到它们在实际代码中被有意使用,而且理由充分。@T.J.Crowder我没有用例。我编写了一个decorator来验证分配给修饰属性的值的类型,这就引出了这个问题,因为“reflect metadata”为
String()
new String()
返回相同的类型,因此,我无法正确验证。因为装箱和取消装箱在JavaScript中是自动的。参见参考文献示例。@Paleo-True,但您可以看到RagnarLodbrok的观点<代码>常量myString:String='str'(或
=String('str')
,这是相同的东西)将一个基本字符串分配给一个声明为对象类型的变量(它,因为这是一个运行时的东西,而这些是编译时类型)。我相信TypeScript团队对此有很好的理由(这很可能与拳击有关:-),但是…“我不能”-只要两个类型拥有相同的属性,它们就属于TS的相同类型。