Skip to content

Commit

Permalink
feat: add isPromise type guard
Browse files Browse the repository at this point in the history
  • Loading branch information
unional committed Jan 31, 2019
1 parent 894850d commit 969748a
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ Provides additional types and type adjusted utilities for `typescript`

- `literalArray(...entries)`: return an array those items are restricted to the provided literals.

### Promise function

- `isPromise<R>(subject: any)`: `isPromise()` type guard.

### Type manipulation

- `ExcludePropType<T, U>`: excludes type `U` from properties in `T`.
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from './filterKey';
export * from './findKey';
export * from './forEachKey';
export * from './Id';
export * from './isPromise';
export * from './KeyTypes';
export * from './literalArray';
export * from './mapKey';
Expand Down
26 changes: 26 additions & 0 deletions src/isPromise.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import t from 'assert';
import { isPromise } from '.';

test('false if subject is falsy value or non-object', () => {
t.strictEqual(isPromise(undefined), false)
t.strictEqual(isPromise(null), false)
t.strictEqual(isPromise(0), false)
t.strictEqual(isPromise(true), false)
t.strictEqual(isPromise('a'), false)
t.strictEqual(isPromise([]), false)
})

test('false if subject does not have a then function', () => {
t.strictEqual(isPromise({}), false)
})

test('false if subject.then is not a function', () => {
t.strictEqual(isPromise({ then: true }), false)
})

test('type guard as promise', () => {
const subject = { then() { return true } }
if (isPromise(subject)) {
t.strictEqual(subject.then(), true)
}
})
3 changes: 3 additions & 0 deletions src/isPromise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function isPromise<R = any>(subject: any): subject is Promise<R> {
return !!subject && typeof subject.then === 'function'
}
4 changes: 4 additions & 0 deletions src/test-util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ export function isNever(_: never) {
export function isNumber(_: number) {
return true
}

export function isVoid(_: void) {
return true
}

0 comments on commit 969748a

Please sign in to comment.