为什么 TypeScript 不抱怨这个?
async GetCategoriesBySet(set: Set): Promise<Result<Array<ProductCategory>>> {
let categories: Array<ProductCategory> = []
if (!set.theme || !set.subtheme || !set.title) {
return Promise.resolve(new Result<Array<ProductCategory>>({res: null, err: "Set data is not valid"}))
}
categories.push(await this.GetCategory(set.theme, {parent: (await this.GetCategory('Themes')).id}))
return categories
}
返回值 categories
的类型为 Array<ProductCategory>
,而不是 Promise,甚至不是包装Result
类。那么,为什么让我犯这个错误是乐于的呢?(有没有办法让它抱怨?
提前致谢
返回值 category 的类型为 Array,而不是 Promise,
所有async
函数都返回一个Promise
。这是 JavaScript 规范的一部分。如果你返回一个常量,它基本上是Promise.resolve
ed。
当你的函数声明Promise<Result<Array<ProductCategory>>>
返回类型时,你可以返回类型为 Result<Array<ProductCategory>>
的值。
如果我有以下声明:
interface Result<T> {
result: T;
}
我从打字稿编译器收到错误:
Property 'result' is missing in type 'ProductCategory[]'.
您对Result
的定义是什么?