如何使用`awaited`类型来期望两种类型的对象。

huangapple go评论60阅读模式
英文:

how to use the awaited type to expect two types of objects

问题

我偶然发现了Typescript中的Awaited实用工具类型,并想做一个非常简单的示例。有些示例似乎具有类似Rust的风格,可能是Monad。我应该如何在这里正确实现它?

```typescript
type Error = { error_code: number, error_message: string }

export type Response = {
    template_id: number
    user_msg: string
    ssboe: number
    usecs: number
}

export function Heartbeat(usecs: number, ssboe: number): Promise<Response | Error> {

    return new Promise((resolve, reject) => {
        try {
            // 返回你的数据对象,比如 { template_id, ssboe, usecs, user_msg }
        } catch (err) {
            // 返回错误对象,比如 { error_code: 1, error_message: 'some msg' }
        }
    });
}

<details>
<summary>英文:</summary>

I stumbled upon the Awaited utility Type in Typescript and wanted to do a very simple example. Some examples seem to have rust like style and maybe monads. How do I properly implement this here? 

```typescript
type Error = { error_code: number, error_message: string }

export type Response = {

    template_id: number
    user_msg: string
    ssboe: number
    usecs: number
}

export function Heartbeat(usecs: number, ssboe: number):Promise&lt;Response|Error&gt; {

    return new Promise((rs, rj) =&gt; {
try {
 return { template_id, ssboe, usecs, user_msg }
catch (err){
return {error_code:1, error_message: &#39;some msg&#39;}
}

}))

}

答案1

得分: 1

从我的理解来看,Awaited&lt;T&gt; 类型更像是一个内部工具类型,而不是开发人员需要使用的类型。它的主要目的是递归解包链接或嵌套的 Promise 值,这在正确地对JavaScript API(如 Promise.allPromise.race 等)的类型进行推断时非常有用。

因此,您可以在技术上使用 Awaited&lt;T&gt; 来解包 Promise 的结果类型,如下所示:

type MyPromise = Promise&lt;string&gt;;
type Value = Awaited&lt;MyPromise&gt;; // string

然而,在我看来,这是一种代码异味,有更好的语言构造可以用来提取或推断 Promise&lt;T&gt; 的结果类型。TypeScript 已经在 Promise 接口中内部使用了 Awaited&lt;T&gt;,因此几乎没有真正需要自己使用它的情况。

至于您的示例,我不确定您所说的“properly implement”是什么意思,或者为什么您需要使用 Awaited&lt;T&gt; 类型。我唯一能看到的问题是,您没有使用“resolve”和“reject”函数来履行 Promise,而且在结果类型中包括 Error 通常被认为是代码异味。它应该看起来像这样:

export function Heartbeat(usecs: number, ssboe: number): Promise&lt;Response&gt; {
    return new Promise((rs, rj) =&gt; {
        try {
            return rs({ ssboe, usecs, user_msg: &quot;&quot;, template_id: 0 });
        } catch (err) {
            return rj({ error_code: 0, error_message: &quot;&quot; });
        }
    });
}

目前,TypeScript 不允许您将拒绝/异常类型指定为 Error 的原因是异常可能从 Promise 执行的深处传播。因此,在设计时,类型检查器无法保证捕获的异常将是 Error 类型,而且除非非常简单的示例,开发人员也无法保证。

英文:

From my understanding, the Awaited&lt;T&gt; type is more of an internal utility type than one that developers should need to reach for. Its main purpose is to recursively unwrap the value of chained or nested promises, which was useful in correctly typing JavaScript APIs like Promise.all, Promise.race, and more.

So you can technically use Awaited&lt;T&gt; to unwrap the result type of a Promise like so:

type MyPromise = Promise&lt;string&gt;;
type Value = Awaited&lt;MyPromise&gt;; // string

However, in my opinion, this is a code smell, and there are better language constructs for extracting or deducing the result type of a Promise&lt;T&gt;. Typescript already internally uses Awaited&lt;T&gt; in the Promise interface, so there aren't many genuine cases for using it yourself.

As for your example, I'm not sure what you mean by "properly implement" it, or why you would need to use the Awaited&lt;T&gt; type. The only problem I can see with your code is that you don't use the "resolve" and "reject" functions to fulfill the Promise, and including Error in your result type is also generally considered a code smell. It should look something like:

export function Heartbeat(usecs: number, ssboe: number): Promise&lt;Response&gt; {
    return new Promise((rs, rj) =&gt; {
        try {
            return rs({ ssboe, usecs, user_msg: &quot;&quot;, template_id: 0 });
        } catch (err) {
            return rj({ error_code: 0, error_message: &quot;&quot; });
        }
    });
}

Currently, the reason TypeScript doesn't let you specify the reject/exception type as Error is because exceptions can propagate deep from within a promise's execution. So at design time, the type checker can't guarantee the caught exception will be of type Error, and besides very trivial examples, neither can the developer.

huangapple
  • 本文由 发表于 2023年6月11日 19:42:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定