此示例使用接口并引发错误(try this example):
// @flow
interface ExtraField {
note: string;
}
type Success = ExtraField & { success: true, value: boolean };
type Failed = { success: false, error: string };
type Response = Success | Failed;
function handleResponse(response: Response) {
if (response.success) {
var value: boolean = response.value;
} else {
var error: string = response.error; // Error!
}
}
错误是:
Cannot get `response.error` because: Either property `error` is missing in `ExtraField` [1]. Or property `error` is missing in object type [2]
注释:
从interface
切换到type
时,错误消失了,即,将ExtraField
编写为:
type ExtraField = {
note: string
}
@AluanHaddad发现了另外两项奇怪的内容(try the different cases here):
if (response.success) {
更改为if (!!response.success) {
时,错误将保留。if (response.success) {
更改为if (response.success === true) {
时,错误将消失。我不太明白为什么interface
在这里不起作用。错误很奇怪。字段error
没有出现在ExtraField
中。
答案 0 :(得分:1)
Flow中的交叉点类型似乎“严重损坏”(see this GitHub issue)。我认为,如果使用对象类型散布,则示例应该更好。
// @flow
interface ExtraField {
note: string,
}
type Success = { success: true, value: boolean };
type Failed = { ...ExtraField, success: false, error: string };
type Response = Success | Failed;
function handleResponse(response: Response) {
if (response.success) {
var value: boolean = response.value;
} else {
var error: string = response.error;
}
}