【发布时间】:2022-01-26 22:18:33
【问题描述】:
我有两个要调用的异步 get,第二个使用第一个的输出,它们返回的类型(在 Promise 中)是不同的。
这些来自 React 中的 AsyncStorage 库。
我的代码是:
function fetchAllSecretsRaw(): Promise<[string, string | null][]> {
return AsyncStorage.getAllKeys().then((allKeys) => {
return AsyncStorage.multiGet(allKeys.filter(isSecretKey));
});
}
我很惊讶在查看 Promise 声明时这种类型检查。这是如何运作的? Promise<[string, string | null][]>如何满足Promise<string[]>(来自TResult1 = T?
异步函数签名是:
getAllKeys(callback?: (error?: Error, keys?: string[]) => void): Promise<string[]>;
multiGet(
keys: string[],
callback?: (errors?: Error[], result?: [string, string | null][]) => void
): Promise<[string, string | null][]>;
而 .then 在Promise<T> 上是:
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
第一个getAllKeys() 给了我一个Promise<string[]>,根据Promise 声明,这意味着T=string[]
既然TResult1 = T(从那时的声明then<TResult1 = T,)这是否意味着TResult1 = string[]?
但我传递的onfulfilled 函数实际上返回一个Promise<[string, string | null][]>,即一个元组数组而不是字符串数组。
【问题讨论】:
标签: typescript promise typescript-generics