Flowtype:如果类型没有匹配字段,则不相交的联合区分不起作用
Flowtype: Disjoint union differentiation doesn't work if types don't have a matching field
我有一个函数应该根据该参数上是否存在字段来处理它作为参数接收的对象。
我创建了以下示例 (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!
}
}
我在指定行中得到的错误是:
Cannot get `response.error` because property `error` is missing in `Success` [1].
不幸的是,我没有具有不同值的共享密钥,这将帮助我区分 Success
和 Failed
对象。
或者有其他方法可以让它工作吗?
您必须使用精确类型。在下面有关 disjoint unions with exact type.
的部分中进一步说明
必须添加带有 |
的精确类型,并且 if/else 必须变成 if/else if。此代码现在不再抛出任何错误 (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 指点我这个答案!
我有一个函数应该根据该参数上是否存在字段来处理它作为参数接收的对象。
我创建了以下示例 (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!
}
}
我在指定行中得到的错误是:
Cannot get `response.error` because property `error` is missing in `Success` [1].
不幸的是,我没有具有不同值的共享密钥,这将帮助我区分 Success
和 Failed
对象。
或者有其他方法可以让它工作吗?
您必须使用精确类型。在下面有关 disjoint unions with exact type.
的部分中进一步说明必须添加带有 |
的精确类型,并且 if/else 必须变成 if/else if。此代码现在不再抛出任何错误 (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 指点我这个答案!