Skip to content

Instantly share code, notes, and snippets.

@MikeyBurkman
Last active July 16, 2019 21:43
Show Gist options
  • Save MikeyBurkman/c85ce27687fa7394c837ec7dfee63aa9 to your computer and use it in GitHub Desktop.
Save MikeyBurkman/c85ce27687fa7394c837ec7dfee63aa9 to your computer and use it in GitHub Desktop.
import * as _ from 'lodash';
/**
* Checks to see if a value is defined (not null/undefined) on a given object.
* Is a type-guard function, so the argument will be cast to a version of itself
* where that field is no longer nullable.
* @example
* type Foo = { x?: string }
* const foo: Foo = ...
* if (isDefined(foo, 'x')) {
* console.log(foo.x.length)
* }
*/
export const isDefined = <T extends object, F extends keyof T>(
t: T,
field: F
): t is T & Required<Pick<T, F>> => {
return !!_.isNil(t[field]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment