diff --git a/index.d.ts b/index.d.ts index b73bef1bd..4ef4b18b7 100644 --- a/index.d.ts +++ b/index.d.ts @@ -9,6 +9,7 @@ export {MergeExclusive} from './source/merge-exclusive'; export {RequireAtLeastOne} from './source/require-at-least-one'; export {ReadonlyDeep} from './source/readonly-deep'; export {LiteralUnion} from './source/literal-union'; +export {Promisable} from './source/promisable'; // Miscellaneous export {PackageJson} from './source/package-json'; diff --git a/readme.md b/readme.md index f0c846bb6..ff3840c2b 100644 --- a/readme.md +++ b/readme.md @@ -71,6 +71,7 @@ Click the type names for complete docs. - [`RequireAtLeastOne`](source/require-at-least-one.d.ts) - Create a type that requires at least one of the given properties. - [`ReadonlyDeep`](source/readonly-deep.d.ts) - Create a deeply immutable version of a `object`/`Map`/`Set`/`Array` type. - [`LiteralUnion`](source/literal-union.d.ts) - Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). +- [`Promisable`](source/promisable.d.ts) - Create a type that represents either the value or the value wrapped in `PromiseLike`. ### Miscellaneous diff --git a/source/promisable.d.ts b/source/promisable.d.ts new file mode 100644 index 000000000..71242a5db --- /dev/null +++ b/source/promisable.d.ts @@ -0,0 +1,23 @@ +/** +Create a type that represents either the value or the value wrapped in `PromiseLike`. + +Use-cases: +- A function accepts a callback that may either return a value synchronously or may return a promised value. +- This type could be the return type of `Promise#then()`, `Promise#catch()`, and `Promise#finally()` callbacks. + +Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31394) if you want to have this type as a built-in in TypeScript. + +@example +``` +import {Promisable} from 'type-fest'; + +async function logger(getLogEntry: () => Promisable): Promise { + const entry = await getLogEntry(); + console.log(entry); +} + +logger(() => 'foo'); +logger(() => Promise.resolve('bar')); +``` +*/ +export type Promisable = T | PromiseLike; diff --git a/test-d/promisable.ts b/test-d/promisable.ts new file mode 100644 index 000000000..34535fbd3 --- /dev/null +++ b/test-d/promisable.ts @@ -0,0 +1,5 @@ +import {expectType} from 'tsd'; +import {Promisable} from '..'; + +declare const promisable: Promisable; +expectType | string>(promisable);