gpt4 book ai didi

typescript - 如何定义 `Promise.all` 的返回类型?

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

不知道这里发生了什么。我对我的类型做了什么奇怪的事情......

const reflect = (promise): Promise<Reflection> =>
promise.then(
(value) => ({ value, resolved: true }),
(error) => ({ error, rejected: true })
);

const to = (promiseArr) => {
return Promise.all(promiseArr.map(reflect)).then((sources: Reflection[]) => sources);
};
Argument of type '(sources: Reflection[]) => Reflection[]' is not assignable to parameter of type '(value: [unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown]) => Reflection[] | PromiseLike<Reflection[]>'.
Types of parameters 'sources' and 'value' are incompatible.
Type '[unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown]' is not assignable to type 'Reflection[]'.
Type 'unknown' is not assignable to type 'Reflection'.ts(2345)

最佳答案

这取决于你的 Reflection type 是,但听起来它可能应该采用解析值的类型参数,如果 Promise 解析,可能类似于

type Reflection<T> = {
value: T;
resolved: true;
} | {
error: unknown;
rejected: true;
}

然后,在 reflectto ,确保表示参数的类型,并将这些类型作为类型参数传递:
const reflect = <T>(promise: Promise<T>): Promise<Reflection<T>> =>
promise.then(
value => ({ value, resolved: true }),
error => ({ error, rejected: true })
);

const to = <T>(promiseArr: Array<Promise<T>>) => {
return Promise.all(promiseArr.map(reflect)).then((sources: Array<Reflection<T>>) => sources);
};

这编译正确,TS 检测到 to的类型为:
const to: <T>(promiseArr: Promise<T>[]) => Promise<Reflection<T>[]>

不过,请注意最后一个 .thento没有做任何事情,因此您可以将其简化为
const to = <T>(promiseArr: Array<Promise<T>>) => {
return Promise.all(promiseArr.map(reflect))
};

Working demo

关于typescript - 如何定义 `Promise.all` 的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60538005/

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