我可以将类型作为泛型参数进行传递,但是当我使用包含类型化参数的对象时,Flow不会理解并且不会建议类型。相反,我得到一个错误。
export type TAction<T, R> = { +type: string, payload?: T, meta?: R };
function thisWorks(action: TAction<string, boolean>) {
const {
payload,
meta,
} = action;
// Flow knows payload is string and meta a boolean
}
function doesntWork(action: TAction<{ prop1: string, prop2: string }, boolean>) {
const {
payload: { prop1, prop2 },
meta,
} = action;
// Flow doesn't know the type of prop1, prop2 or meta
}
流错误为:
prop1
中缺少属性TAction
[1] .Flow(InferError)
答案 0 :(得分:1)
我创建了尝试说明上述问题的流程:Try it here
从中我可以看到,问题是在TAction
中,元数据和有效载荷都被注释为optional properties。这就是为什么在分解有效负载之前需要对其进行检查的原因,而不是undefined
。如下代码将不会出现流错误:
export type TAction<T, R> = { +type: string, payload?: T, meta?: R };
function thisWorks(action: TAction<string, boolean>) {
const {
payload,
meta,
} = action;
// Flow knows payload is string and meta a boolean
}
function doesntWork(action: TAction<{| prop1: string, prop2: string |}, boolean>
) {
const {
payload,
meta,
} = action;
if (payload) {
const { prop1, prop2 } = payload;
// Do whatever is needed
}
}
或者可以更改TAction
的注释,因此payload
和meta
将不再是可选属性,如下所示:
export type TAction<T, R> = { +type: string, payload: T, meta: R };
function thisWorks(action: TAction<string, boolean>) {
const {
payload,
meta,
} = action;
// Flow knows payload is string and meta a boolean
}
function doesntWork(action: TAction<{| prop1: string, prop2: string |}, boolean>
) {
const {
payload: { prop1, prop2 },
meta,
} = action;
// Flow doesn't know the type of prop1, prop2 or meta
}