Skip to content

Instantly share code, notes, and snippets.

@aiya000
Created November 30, 2020 10:44
Show Gist options
  • Save aiya000/9b3c64a44aa36698b9d8d7b8609626f3 to your computer and use it in GitHub Desktop.
Save aiya000/9b3c64a44aa36698b9d8d7b8609626f3 to your computer and use it in GitHub Desktop.
/**
* 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