From 577c2a24f524687b8bce42f3dc8ce90b1c5c8d7b Mon Sep 17 00:00:00 2001 From: onichandame Date: Sun, 28 Jun 2020 04:53:28 +0800 Subject: [PATCH] Make the `PromiseValue` type handle nested promises (#112) Co-authored-by: Sindre Sorhus --- source/promise-value.d.ts | 9 ++++++++- test-d/promise-value.ts | 4 ++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/source/promise-value.d.ts b/source/promise-value.d.ts index 7686dd11d..642ddebcc 100644 --- a/source/promise-value.d.ts +++ b/source/promise-value.d.ts @@ -1,5 +1,6 @@ /** Returns the type that is wrapped inside a `Promise` type. +If the type is a nested Promise, it is unwrapped recursively until a non-Promise type is obtained. If the type is not a `Promise`, the type itself is returned. @example @@ -15,6 +16,12 @@ let data: Data = await asyncData; // Here's an example that shows how this type reacts to non-Promise types. type SyncData = PromiseValue; let syncData: SyncData = getSyncData(); + +// Here's an example that shows how this type reacts to recursive Promise types. +type RecursiveAsyncData = Promise >; +let recursiveAsyncData: PromiseValue = Promise.resolve(Promise.resolve('ABC')); ``` */ -export type PromiseValue = PromiseType extends Promise ? Value : Otherwise; +export type PromiseValue = PromiseType extends Promise + ? { 0: PromiseValue; 1: Value }[PromiseType extends Promise ? 0 : 1] + : Otherwise; diff --git a/test-d/promise-value.ts b/test-d/promise-value.ts index 7a91156e6..76f866c48 100644 --- a/test-d/promise-value.ts +++ b/test-d/promise-value.ts @@ -2,11 +2,15 @@ import {expectAssignable} from 'tsd'; import {PromiseValue} from '..'; type NumberPromise = Promise; +type NestedPromise = Promise; type Otherwise = object; // Test the normal behaviour. expectAssignable>(2); +// Test the nested behaviour. +expectAssignable>(2); + // Test what happens when the `PromiseValue` type is not handed a `Promise` type. expectAssignable>(2);