Flowtype:如果类型没有匹配的字段,则不相交联合区分不起作用 [英] Flowtype: Disjoint union differentiation doesn't work if types don't have a matching field
问题描述
我有一个函数,该函数应根据此参数上是否存在字段来不同地处理作为参数接收的对象.
I have a function which should handle an object it receives as a parameter differently depending on whether a field exists on this parameter.
我创建了下面的例子(自己尝试的) - 它是在一示例的适配关于不忠联盟类型的流类型文档:>
I created the following example (try it yourself) - it's an adaptation of an example in the flow type docs about disjount union types:
// @flow
type Success = { value: boolean };
type Failed = { error: string };
type Response = Success | Failed;
function handleResponse(response: Response) {
if (response.value) {
var value = response.value;
} else {
var error = response.error; // Error!
}
}
我在指定行中得到的错误是:
The error I get in the denoted line is:
Cannot get `response.error` because property `error` is missing in `Success` [1].
很不幸,我没有一个具有不同值的共享密钥,这可以帮助我区分Success
和Failed
对象.
I unfortunately don't have a shared key with different values which would help me to differentiate between the Success
and Failed
objects.
还是有其他方法可以使其正常工作?
Or is there an alternative way to get it working?
推荐答案
您必须使用确切类型.下文在精确类型的不相交联合.
必须添加带有|
的精确类型,并且if/else必须变为if/else if.此代码现在不会引发任何错误了(尝试新的代码):
Exact types with |
have to be added and the if/else has to turn into an if/else if. This code now does not throw any errors anymore (try the new code):
// @flow
type Success = {| value: boolean |};
type Failed = {| error: string |};
type Response = Success | Failed;
function handleResponse(response: Response) {
if (response.value) {
var value: boolean = response.value;
} else if (response.error) {
var error: string = response.error; // Error!
}
}
感谢@ user11307804向我指出此答案!
Thanks @user11307804 for pointing me to this answer!
这篇关于Flowtype:如果类型没有匹配的字段,则不相交联合区分不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!