我在使用下面这样的typeof
时出错。
function func (variable: number | string) {
const is_number = (typeof variable === 'number');
let variable2: number,
variable3: string;
if (is_number)
variable2 = variable;
=> Type 'string | number' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
else
variable3 = variable;
=> Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
}
但是,没有下面这样的错误。
function func (variable: number | string) {
let variable2: number,
variable3: string;
if (typeof variable === 'number')
variable2 = variable;
else
variable3 = variable;
}
URL for test
我总是要像上面那样使用它吗?或者有什么地方我用错了?
感谢阅读:)
最佳答案
@已经回答了评论中的实际问题。下面是限制的解决办法。
可以用一个助手函数来实现类似的事情,我将调用“cc>”,它断定某个给定的参数是否是cc>某个类型的类型。这提供了一种不允许像jcc>那样内嵌JS域类型断言的方法。相反,断言现在包含在函数中。
这是使用isNumber
构造完成的,称为Type predicate(您必须向下滚动一点)。在下面的代码片段中,extends
的返回类型是这样一个类型谓词:
const isNumber = (subject: any): subject is number => {
return typeof subject === 'number';
};
这里,typescript可以从
typeof variable === "number"
返回的布尔值推断x is y
类型。现在,如果您在自己的isNumber
中使用这个helper函数,那么一切都应该是好的:function func (variable: number | string) {
let variable2: number;
let variable3: string;
if (isNumber(variable)) {
variable2 = variable;
} else {
variable3 = variable;
}
}
由于只有当
number
返回true时才会执行isNumber
块,typescript现在将假定func
。下面的伪代码演示了TS应如何解释上述代码:if (variable is number) {
// ...
}
我还发现this SO answer进一步解释了类型谓词构造。
关于javascript - 分配给变量时,typeof typeguard是否不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50303925/