gpt4 book ai didi

javascript - 在 Flow 中传递通用参数对象

转载 作者:行者123 更新时间:2023-11-30 11:06:28 25 4
gpt4 key购买 nike

我可以将类型作为通用参数传递,但是当我使用包含类型化参数的对象时,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
}

流错误是:

property prop1 is missing in TAction [1].Flow(InferError)

最佳答案

我已经创建了流程来尝试说明上述问题:Try it here

从中我可以看出,问题是在 TAction 中,meta 和 payload 都被注释为 optional properties .这就是为什么在解构 payload 之前需要对其进行检查,确保它不是 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
}
}

Try with flow

或者可以更改 TAction 的注释,因此 payloadmeta 将不再是可选属性,如下所示:

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
}

Try with flow

关于javascript - 在 Flow 中传递通用参数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55419458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com