Created
November 30, 2020 10:44
-
-
Save aiya000/9b3c64a44aa36698b9d8d7b8609626f3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Exposes type utility functions. | |
* @packageDocumentation | |
*/ | |
/** | |
* Does `x` have an undefined property `prop`, | |
* or that property is `PropType`? | |
* | |
* @example | |
* ``` | |
* import { equal } from 'assert' | |
* import { haveUndefienedPropertyOrThat } from './types' | |
* | |
* interface Foo { | |
* bar: number | |
* } | |
* | |
* function isFoo(x: unknown): x is Foo { | |
* return ( // a better predicate. | |
* x instanceof Object && | |
* typeof (x as { bar?: number }).bar === 'number' | |
* ) | |
* } | |
* | |
* equal(haveUndefienedPropertyOrThat(isFoo, {bar: undefined}, 'bar'), true) | |
* equal(haveUndefienedPropertyOrThat(isFoo, {bar: 10}, 'bar'), true) | |
* equal(haveUndefienedPropertyOrThat(isFoo, {bar: 'bar'}, 'bar'), false) | |
* ``` | |
*/ | |
export function haveUndefienedPropertyOrThat< | |
PropType, | |
Base, | |
Prop extends string | |
>(p: (a: unknown) => a is PropType, x: Base, prop: Prop): boolean { | |
const xx = x as {[P in Prop]?: unknown} | |
return xx[prop] === undefined || p(x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment