gpt4 book ai didi

javascript - 区分联合类型时出现错误 ("property not found in object type")

转载 作者:行者123 更新时间:2023-12-01 03:00:35 24 4
gpt4 key购买 nike

我很难描述函数参数的类型,它要么是成功,要么是错误 api 响应。这是该问题的一个简单的令人费解的示例(在 TryFlow 中复制于 this address )

该函数可以采用成功响应对象或错误响应对象:

export type ErrorResponse = {
error: {
message: string,
}
}

export type SuccessResponse = {
token: {
id: string,
}
}

然后它应该决定它是哪种类型的响应,并将响应传递给 handleSuccesshandleError 函数:

function onSubmit(response: SuccessResponse | ErrorResponse) {
if (response.error) {
handleError(response);
} else {
handleSuccess(response);
}
}

function handleError(response: ErrorResponse) {
console.log(response.error.message);
}

function handleSuccess(response: SuccessResponse) {
console.log(response.token.id);
}

问题是,Flow 出现错误:

23: function handleError(response: ErrorResponse) {
^ property `error`. Property not found in
17: handleError(response);
^ object type

如果我将响应对象输入为交集类型 (SuccessResponse & ErrorResponse),而不是联合类型 (SuccessResponse | ErrorResponse),错误就会消失,但这可以不对 — 我没有向 onSubmit 函数传递一个具有两种类型的所有属性的对象,而是传递一个可以是任一的参数> 两种类型。

您能否解释一下我做错了什么,并就如何修复此打字错误提出建议?

最佳答案

您遇到的问题是 Flow 不知道 SuccessResponse 是否具有可能的额外 error 参数。

要告诉 Flow 没有,您可以输入 exact Object types :

export type ErrorResponse = {|
error: {
message: string,
},
|}

export type SuccessResponse = {|
token: {
id: string,
},
|}

关于javascript - 区分联合类型时出现错误 ("property not found in object type"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46447962/

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