From c686efd51b363aabc981340a7fd85dacdb04d26d Mon Sep 17 00:00:00 2001 From: MikeDimmickMnetics Date: Fri, 19 Jan 2018 20:22:15 +0000 Subject: [PATCH] [q] Allow thenReject to return a promise for a different type (#23029) * Change the Promise.thenReject signature to allow matching of a different type. Type-checking rejections is problematic as it's equivalent to `throw`: you don't get a value of type T in your success callback. You get an Error (or other thrown type) in an error callback. --- types/q/index.d.ts | 2 +- types/q/q-tests.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/types/q/index.d.ts b/types/q/index.d.ts index f7158f7436..724925d802 100644 --- a/types/q/index.d.ts +++ b/types/q/index.d.ts @@ -145,7 +145,7 @@ declare namespace Q { /** * A sugar method, equivalent to promise.then(function () { throw reason; }). */ - thenReject(reason?: any): Promise; + thenReject(reason?: any): Promise; /** * Attaches a handler that will observe the value of the promise when it becomes fulfilled, returning a promise for that same value, perhaps deferred but not replaced by the promise returned diff --git a/types/q/q-tests.ts b/types/q/q-tests.ts index 8489625736..c0c29d9642 100644 --- a/types/q/q-tests.ts +++ b/types/q/q-tests.ts @@ -234,3 +234,37 @@ Q.try(() => { return true; }) .catch((error) => console.error("Couldn't sync to the cloud", error)); + +// thenReject, returning a Promise of the same type as the Promise it is called on +function thenRejectSameType(arg: any): Q.Promise { + if (!arg) { + return returnsNumPromise('') + .thenReject(new Error('failed')); + } + return Q.resolve(2); +} + +// thenReject, returning a Promise of a different type to the Promise it is called on. +// The generic type argument is specified. +function thenRejectSpecificOtherType(arg: any): Q.Promise { + if (!arg) { + return returnsNumPromise('') + .thenReject(new Error('failed')); + } + return Q.resolve(''); +} + +// thenReject, returning a Promise of a different type to the Promise it is called on. +// The generic type argument is inferred. +// This relies on 'Return types as inference targets', new in TS 2.4. +// Commented out as we support TS 2.3. +// This should be uncommented if the minimum version is changed. +/* +function thenRejectInferredOtherType(arg: any): Q.Promise { + if (!arg) { + return returnsNumPromise('') + .thenReject(new Error('failed')); + } + return Q.resolve(''); +} +*/