gpt4 book ai didi

javascript - typescript 理解不可分配的参数

转载 作者:行者123 更新时间:2023-11-30 08:19:07 26 4
gpt4 key购买 nike

假设我有以下内容

const client: Client | boolean = await db.connect()
if (client === false) {
return
}

await start(client)

db.connect() 要么返回客户端(连接成功)要么返回 false(连接失败)。

start 只接受 Client 作为参数:

const start = async (dbClient: Client): Promise<void> => {

正如您可能看到的那样,await start(client) 出现错误:

Argument of type true | Client is not assignable to type Client

我可以通过指定 Client | 的类型来解决这个问题start 中的 boolean 并且知道它永远不会为 false 是安全的,因为它在调用 start 之前提前返回,并且永远不会为 true 因为 connect 永远不会返回 true,但这有异味(并且可能导致进一步的问题)。

这种事情的最佳方法/实践是什么?

我可以返回一个对象,而不仅仅是从 connect 返回 Client

{
connected: boolean,
client: client,
}

这样更有意义吗?

最佳答案

因为您知道它只能是 Client 或 false,所以您可以将其编码为类型 Client |错误。然后 TypeScript 足够聪明,可以计算出如果你排除 false,剩下的就是 Client

type ClientResult = Client | false;
const client: ClientResult = await db.connect()
if (client === false) {
return
}

await start(client)

关于javascript - typescript 理解不可分配的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56994425/

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