【发布时间】:2020-11-21 08:33:11
【问题描述】:
下面,将字符串文字分配给基本(原始)类型string 的变量很好:let s3: string = "s"。
但是 TypeScript 不应该禁止将字符串文字分配给非基本 String 类型的变量:let s1: String = "s"?特别是,考虑到后面的s1 instanceof String 是false:
let s1: String = "s"; // no error here
let s2: String = new String("s");
let s3: string = "s";
console.log(s1 instanceof String) // false
console.log(s2 instanceof String) // true
console.log(s1 === s2); // false
console.log(s1 === s3); // true;
console.log(typeof(s1)) // "string"
console.log(typeof(s2)) // "object"
console.log(typeof(s3)) // "string"
//console.log(s3 instanceof string) // error
生成的JS代码是这样的(TS 4.0,-t ESNext t.ts):
let s1 = "s"; // no error here
let s2 = new String("s");
let s3 = "s";
console.log(s1 instanceof String); // false
console.log(s2 instanceof String); // true
console.log(s1 === s2); // false
console.log(s1 === s3); // true;
console.log(typeof (s1)); // "string"
console.log(typeof (s2)); // "object"
console.log(typeof (s3)); // "string"
//console.log(s3 instanceof String) // error
我了解这段 JavaScript 代码的工作原理,但为什么 TS 默认会这样生成它:原始值而不是 String 的隐式实例。我宁愿期待let s1 = new String("s"),或者一个错误。
我的意思是,如果变量 v 在 TypeScript 中是非基本类型 Type,我希望 v instanceof Type 是 true,但 s1 不是这种情况。
这种行为是否在某处的规范中定义?
【问题讨论】:
-
这很奇怪!如果你认为 (s1 instanceof String) 应该是真的,会导致很多问题!
-
有趣。但是你真的在某个地方使用
new String吗? (只是好奇) -
@AlekseyL.,不是真的,我偶然遇到了这个。此外,我在 vanilla JavaScript 中比在 TypeScript 中做的工作更多,每当我需要检查某个东西是否是字符串时,我都学会了这样做:
stringVar.constructor === String。这也适用于全面和 TS (fiddle)。它不适用于跨领域,但这个可以:stringVar.constructor.name === 'String'。 -
你居然忘记了一个案例:
let s4: string = String("s");:-) -
我想他们故意提供了从
string到String的隐式转换,但反之亦然。 ` 让我们:字符串 = '';让 ss = 'aaa'; s = ss; ss = s; ` 最后一行有错误Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.ts(2322)
标签: javascript typescript