From c24d865eb6c122932e2af0d9052abdb58ead5ab4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustaf=20R=C3=A4ntil=C3=A4?= Date: Wed, 8 May 2019 17:30:14 +0200 Subject: [PATCH] feat(types): Added meta functions PromiseOf and PromiseElement --- README.md | 25 +++++++++++++++++++++++++ lib/index.ts | 19 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/README.md b/README.md index bedb21d..f61b514 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,10 @@ The functions are standalone and depends on no particular Promise implementation This library is written in TypeScript but is exposed as ES7 (if imported as `already`) and ES5 (if imported as `already/es5`). Typings are provided too, so any TypeScript project using this library will automatically get full type safety of all the functions. +# Types + * [PromiseOf\](#PromiseOf) + * [PromiseElement\](#PromiseElement) + # Functions * [delay](#delay) @@ -33,6 +37,27 @@ This library is written in TypeScript but is exposed as ES7 (if imported as `alr * [wrapFunction](#wrapfunction) * [funnel](#funnel) +--- + +# Types + +## PromiseOf + +`PromiseOf< P >` returns the Promise wrapped value of `P`, unless it's already a promise, where the promise itself is returned instead. + + * For `P` (being `Promise< E >`), it returns `P` + * For non-promise `P`, it returns `Promise< P >` + + +## PromiseElement + +`PromiseElement< P >` returns the element type of a promise, or the type itself if it isn't wrapped in a promise. + + * For `P` (being `Promise< E >`), it returns `E` + * For non-promise `P`, it returns `P` + + +# Functions ## delay diff --git a/lib/index.ts b/lib/index.ts index af23639..6f758a3 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -24,6 +24,25 @@ export default { }; +/** + * Returns the Promise wrapped value of P, unless it's already a promise, where + * the promise itself is returned instead. + * + * For P being Promise, it returns P + * For non-promise P, it returns Promise

+ */ +export type PromiseOf< P > = P extends Promise< infer U > ? P : Promise< P >; + +/** + * Returns the element type of a promise, or the type itself if it isn't + * wrapped in a promise. + * + * For P being Promise, it returns E + * For non-promise P, it returns P + */ +export type PromiseElement< P > = P extends Promise< infer U > ? U : P; + + function toReadonlyArray< T >( arr: ConcatArray< T > ): ReadonlyArray< T > { /* istanbul ignore else */