我有一个可能的计算不确定
或 null
值的布尔值。即使检查组成的布尔值是否为真,Typescript也不明白该值不能再 null null 。
在下面的示例中, externativetoanothermaybenulluldullunderfined的类型||在IF分支中,将另一个maybenullorundefined
评估为可能未定义,这导致错误类型'undefined'的参数不能分配给类型'string'''''String''
的参数,但是我已经检查了在非卢洛德定义
。
const maybeNullOrUndefined: string | undefined | null = undefined;
const anotherMaybeNullOrUndefined: string | undefined | null = undefined;
const alternativeToAnotherMaybeNullOrUndefined: string | undefined | null = undefined;
const anyFun = (str: string) => { }
const noNullOrUndefined = (anotherMaybeNullOrUndefined || alternativeToAnotherMaybeNullOrUndefined) && maybeNullOrUndefined;
if (noNullOrUndefined) {
anyFun(maybeNullOrUndefined);
anyFun(alternativeToAnotherMaybeNullOrUndefined || anotherMaybeNullOrUndefined); // Argument of type 'undefined' is not assignable to parameter of type 'string'
}
这只是一个构造的示例,但就我而言,即使我以前我在布尔值中检查了,即使是 Maybenullorundefined
也可能是未定义的类型。为什么那是这样,我该如何克服?
I have a composed computed boolean of possible undefined
or null
values. Even though checking if the composed boolean is true, typescript doesn't understand that the values cannot be undefined
or null
anymore.
In the following example, the type of alternativeToAnotherMaybeNullOrUndefined || anotherMaybeNullOrUndefined
inside the if branch is evaluated to possibly undefined, which results in error Argument of type 'undefined' is not assignable to parameter of type 'string'
, but I am already checking alternativeToAnotherMaybeNullOrUndefined
and anotherMaybeNullOrUndefined
in noNullOrUndefined
.
const maybeNullOrUndefined: string | undefined | null = undefined;
const anotherMaybeNullOrUndefined: string | undefined | null = undefined;
const alternativeToAnotherMaybeNullOrUndefined: string | undefined | null = undefined;
const anyFun = (str: string) => { }
const noNullOrUndefined = (anotherMaybeNullOrUndefined || alternativeToAnotherMaybeNullOrUndefined) && maybeNullOrUndefined;
if (noNullOrUndefined) {
anyFun(maybeNullOrUndefined);
anyFun(alternativeToAnotherMaybeNullOrUndefined || anotherMaybeNullOrUndefined); // Argument of type 'undefined' is not assignable to parameter of type 'string'
}
That's just a constructed example, but in my case, even maybeNullOrUndefined
is evaluated to be possibly of type undefined, even though I am checking it in a boolean before. Why is that and how can I overcome this?
发布评论
评论(1)
TS不会根据这样的条件缩小类型。
您需要定义一个新变量并使用分支来调用您的功能。您在这里有2个选项:
或者
您可以在行动中看到此选项在这里
TS will not narrow the type based on conditions like that.
You need to define a new variable and use a branch to call your function. You have 2 options here:
or
You can see this in action here