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

Tho*_*dez 5 typescript es6-promise

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

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);
};
Run Code Online (Sandbox Code Playgroud)
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)

Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 2

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

type Reflection<T> = {
    value: T;
    resolved: true;
} | {
    error: unknown;
    rejected: true;
}
Run Code Online (Sandbox Code Playgroud)

然后,在reflect和 中to,确保表示参数的类型,并将这些类型作为类型参数传递:

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);
};
Run Code Online (Sandbox Code Playgroud)

这可以正确编译,并且 TS 检测到to的类型为:

const to: <T>(promiseArr: Promise<T>[]) => Promise<Reflection<T>[]>
Run Code Online (Sandbox Code Playgroud)

不过,请注意最后.then一个to没有做任何事情,所以你可以将其简化为

const to = <T>(promiseArr: Array<Promise<T>>) => {
    return Promise.all(promiseArr.map(reflect))
};
Run Code Online (Sandbox Code Playgroud)

工作演示