TypeScript Promise定义通用语法

时间:2019-06-06 07:27:11

标签: typescript promise typescript-typings typescript-generics

我对Promise的{​​{1}}定义如下:

TypeScript

我认为/** * Represents the completion of an asynchronous operation */ interface Promise<T> { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>; } 意味着then<TResult1 = T, TResult2 = never>有两种通用类型,分别是thenTResult1。如果未指定,TResult2将为TResult1

但是事实证明,T将根据TResult1的{​​{1}}进行更改。观看演示:

return type

onfulfilledinterface Result { status: number; message: string; } function foo() { return new Promise<Result>(function (resolve, reject) { resolve({ status: 0, message: 'ok', }); }); } // here fulfilled1's type is: (local function) fulfilled(out: Result): number foo().then(function fulfilled1(out) { if (Math.random() > 0.5) { return 1; } }); // here fullfilled2's type is: (local function) fulfilled2(out: Result): string foo().then(function fulfilled2(out) { if (Math.random() > 0.5) { return 'hello'; } }); 都与fulfilled1匹配。但是由于我不区分fulfilled2泛型类型,因此我认为以上代码中的then<TResult1 = T, TResult2 = never>将是then,而实际上TResult1会变成Result和{{ 1}}。

也许我对TResul1 number有误。 任何想法都值得赞赏。

1 个答案:

答案 0 :(得分:1)

当无法对TResult1进行推断时,将使用默认值。在这种情况下,可以根据您传入的函数进行推断。由于then的两个参数都标记为可选,因此这将是有效的调用,并会触发默认值:

 foo().then() // returns a promise with TResult1

或者是一个更有用的示例,仅传入第二个参数,再次TResult1使用默认值。

 var r = foo().then(undefined, r => "ERR"); // Promise<string | Result>

如果您确实传入一个函数,则该函数可以更改返回的Promise的类型,我认为这是大多数人使用Promise,执行异步调用,处理结果,将其他内容返回到下一个的方式结果。