typescript typeof string 不能按预期工作
typescript typeof string doesn't work as expected
谁能解释为什么第二种变体不起作用?这是一个错误吗?
const prints = (s: string): void => console.log(s);
var x: string | number = Date.now() % 2 ? "test" : 5;
// 1st: working
if (typeof x === "string") {
prints(x);
}
// 2nd: not working
var typex = typeof x === "string";
if (typex) {
prints(x);
}
第二个变体显示以下错误:
Argument of type 'string | number' is not assignable to parameter of type 'string'.
Type 'number' is not assignable to type 'string'
TypeScript 不够智能,无法证明第二个 if
中的 x
确实是 string
。由于prints
只接受一个string
,它不能证明x
是一个string
,所以会报错。
第一种情况,类型检查发生在 if
条件本身内部,因为 TypeScript 有 a special case for understanding that kind of type check。但是,理解某个变量中的某些值可以指示某个其他变量的类型的理解超出了它的处理范围。是的,在这个具体的例子中,看起来 弄清楚它应该是微不足道的,但在一般情况下它很快就会变得极其困难甚至完全不可能发挥作用。
如果您绝对希望第二种情况有效,尽管类型检查与 if
是分开的,您需要通过显式转换值来为 TypeScript 提供额外信息。例如,使用 prints(x as string)
表示“我保证它始终是 string
。如果不是,程序爆炸时是我的错。”这种类型的转换是向 TypeScript 发出的信号,表明开发人员知道一些它不理解的东西并盲目地相信它。
如评论中所述,github
上已存在该问题:
Indirect type narrowing via const and allow storing results of narrowing in booleans for further narrowing
谁能解释为什么第二种变体不起作用?这是一个错误吗?
const prints = (s: string): void => console.log(s);
var x: string | number = Date.now() % 2 ? "test" : 5;
// 1st: working
if (typeof x === "string") {
prints(x);
}
// 2nd: not working
var typex = typeof x === "string";
if (typex) {
prints(x);
}
第二个变体显示以下错误:
Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'
TypeScript 不够智能,无法证明第二个 if
中的 x
确实是 string
。由于prints
只接受一个string
,它不能证明x
是一个string
,所以会报错。
第一种情况,类型检查发生在 if
条件本身内部,因为 TypeScript 有 a special case for understanding that kind of type check。但是,理解某个变量中的某些值可以指示某个其他变量的类型的理解超出了它的处理范围。是的,在这个具体的例子中,看起来 弄清楚它应该是微不足道的,但在一般情况下它很快就会变得极其困难甚至完全不可能发挥作用。
如果您绝对希望第二种情况有效,尽管类型检查与 if
是分开的,您需要通过显式转换值来为 TypeScript 提供额外信息。例如,使用 prints(x as string)
表示“我保证它始终是 string
。如果不是,程序爆炸时是我的错。”这种类型的转换是向 TypeScript 发出的信号,表明开发人员知道一些它不理解的东西并盲目地相信它。
如评论中所述,github
上已存在该问题:
Indirect type narrowing via const and allow storing results of narrowing in booleans for further narrowing