Last active
July 16, 2019 21:43
-
-
Save MikeyBurkman/c85ce27687fa7394c837ec7dfee63aa9 to your computer and use it in GitHub Desktop.
This file contains 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
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