不知道这是怎么回事。我对我的类型做了奇怪的事情吗?
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)
答案 0 :(得分:2)
这取决于您的Reflection
类型,但是如果Promise解析,听起来好像应该使用一个resolve值的类型参数,
type Reflection<T> = {
value: T;
resolved: true;
} | {
error: unknown;
rejected: true;
}
然后,在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);
};
这可以正确编译,并且TS将to
的类型检测为:
const to: <T>(promiseArr: Promise<T>[]) => Promise<Reflection<T>[]>
不过,请注意,.then
中的最后一个to
并没有做任何事情,因此您可以将其简化为
const to = <T>(promiseArr: Array<Promise<T>>) => {
return Promise.all(promiseArr.map(reflect))
};