将类型安全超时添加到typescript中的异步函数

发布于 2025-01-30 20:08:06 字数 2521 浏览 2 评论 0原文

今天,我被分配了在我们的回购时间内完成一堆异步功能,如果它们占用了2秒。以此为机会,通过制作一个通用功能来尝试了解我们现有功能并“定时器化”它们,并返回正确的类型,以尝试了解有关打字稿的更多信息。这是我在操场上工作的版本:

type AsyncFn<T> = (...args: any[]) => Promise<T>

class MyClass {
    TIMEOUT = 2 * 1000

    fakePromiseFn(input: string): Promise<string> {
        return new Promise((resolve, reject) => {
            // async stuff
            setTimeout(() => {
                console.log(input)
                resolve(input)
            }, 1000)
        })
    }

    async timedPromiseFn(input: string): Promise<string> {
        // why is result unknown
        const result = await this.time(this.fakePromiseFn.bind(this), input)
        return result
    }

    time<T>(fn: AsyncFn<T>, ...args: any[]): Promise<T> {
        return new Promise(async (resolve, reject) => {
        const timer = setTimeout(() => reject(new Error('timeout')), this.TIMEOUT)
        try {
            const results = await fn(...args)
            resolve(results)
        } catch(err) {
            reject(err)
        } finally {
            clearTimeout(timer)
        }
    })
  }
}

const myClass = new MyClass()

我不知道的是为什么result在我的timedpromisefn键入未知的中? FakePromiseFn的返回时间是Promise&lt; string&gt;,在我的time函数中,将在调用任何asyncfn的结果下解决承诺。传递,asyncfn的返回类型是T。我只是在整个过程中都使用一个T,那么为什么编译器不能推断正确的类型?我做错了什么?

Playground link< /a>

(在操场链接中,它似乎正确地获得了类型的正确性; string&gt; ,因此它将该类型分配给结果。但是,如果您不返回结果它说未知。

Today I was assigned to make a bunch of async functions in our repo time out if they take >2 seconds. Took this as an opportunity to try and learn more about typescript by making a generic function that would take our existing functions and "timer-ify" them, and return the correct type. Here's a version of what I came up with that works in a playground:

type AsyncFn<T> = (...args: any[]) => Promise<T>

class MyClass {
    TIMEOUT = 2 * 1000

    fakePromiseFn(input: string): Promise<string> {
        return new Promise((resolve, reject) => {
            // async stuff
            setTimeout(() => {
                console.log(input)
                resolve(input)
            }, 1000)
        })
    }

    async timedPromiseFn(input: string): Promise<string> {
        // why is result unknown
        const result = await this.time(this.fakePromiseFn.bind(this), input)
        return result
    }

    time<T>(fn: AsyncFn<T>, ...args: any[]): Promise<T> {
        return new Promise(async (resolve, reject) => {
        const timer = setTimeout(() => reject(new Error('timeout')), this.TIMEOUT)
        try {
            const results = await fn(...args)
            resolve(results)
        } catch(err) {
            reject(err)
        } finally {
            clearTimeout(timer)
        }
    })
  }
}

const myClass = new MyClass()

What I can't figure out is why is result in my timedPromiseFn type unknown? The return time of fakePromiseFn is Promise<string>, and in my time function, the promise is resolved with the result of calling whatever AsyncFn is passed in, and the return type of AsyncFn is T. I'm only using one T throughout, so why can't the compiler infer the correct type? What did I do wrong?

Playground link

(in the playground link it seems to get the type right because I return result and it sees that the return type of timedPromiseFn is supposed to be Promise<string> so it just assigns that type to result. But if you don't return result it says unknown.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文