class Base {}
function log(arg: number) {
console.log(arg);
}
function fn<T extends typeof Base>(
instance: Partial<InstanceType<T>>,
key: keyof InstanceType<T>,
) {
const val = instance[key];
if (val) {
log(val);
}
}
我得到:
Argument of type 'InstanceType<T>[keyof InstanceType<T>] | undefined' is not assignable to parameter of type 'number'.
Type 'undefined' is not assignable to type 'number'.
if (val)
不应该防范undefined
吗?如果我将其更改为 log(val ?? 0)
,它就会起作用。
另外,我很惊讶 log(val ?? 0)
有效。 val
可能是一个非数字的真值,但 log()
需要一个数字。为什么这不会引发错误?
最佳答案
问题是well known 。您可以从此comment了解类型检查器内部到底发生了什么。 :
The core problem is that the narrowed type of fooAnchor is not really speakable. Its unnarrowed type is Partial<FooAnchorMap>[keyof TMap], which isn't a union that we can remove undefined and null from to produce some other type that would be provably-assignable to HTMLElement.
有work in progress来解决它。但到目前为止,您只剩下解决方法了。
function fn<T extends typeof Base>(
instance: Partial<InstanceType<T>>,
key: keyof InstanceType<T>,
) {
const val: InstanceType<T>[keyof InstanceType<T>] | undefined = instance[key];
if (val) {
log(val);
}
}
您将得到正确的错误: Type 'InstanceType<T>[string]' is not assignable to type 'number'.
关于javascript - Typescript:检查变量的真实性不会对未定义进行类型防护吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67980758/