流中的条件类型 [英] Conditional types in flow
本文介绍了流中的条件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以根据条件在流中键入变量?这样的事情:
Is it possible to type a variable in flow based on a condition? Something like this:
const type = 'xyz';
const a: (type === 'xyz') ? number : string;
推荐答案
简短的回答是否定的。变量必须绑定到单个类型,其中可以包含类似 number |的联合类型串
。在条件块内部,Flow可以推断出更专业的类型。例如:
The short answer is no. A variable must be bound to a single type, which can include a union type like number | string
. Inside a conditional block Flow can infer a more specialised type. For example:
const a: number | string = "foo";
if(typeof a === "string"){
a.split(); // OK!
} else {
a.split(); // Error! a is a number
}
但请注意这些条件分支是静态的,并且它是有保证的在编译时,每个类型内的类型。
But notice that these conditional branches are static, and it's guaranteed at compile time what the type will be inside each.
这篇关于流中的条件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文