【发布时间】:2019-08-07 12:57:52
【问题描述】:
此示例使用接口并引发错误(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 中。
【问题讨论】:
-
好的,现在重新打开
-
这很令人困惑。看看这段代码(有效)flow.org/try/…
-
它变得更奇怪了flow.org/try/…
-
Flow 中的交叉点类型似乎“严重损坏”(github.com/facebook/flow/issues/6482#issuecomment-421167167)。我认为如果您使用对象类型传播,该示例应该会更好。 Try Flow.
-
同意@user11307804 只是一个提示:始终使用精确类型+传播。尽量不要使用接口、非精确类型和交互类型。
标签: javascript types flowtype