Skip to content

Instantly share code, notes, and snippets.

@kylelambert101
Last active May 13, 2021 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylelambert101/8152b62f27b33152451b04c770dd74fe to your computer and use it in GitHub Desktop.
Save kylelambert101/8152b62f27b33152451b04c770dd74fe to your computer and use it in GitHub Desktop.
TypeScript -> Inline Type Guard
// Source: https://www.benmvp.com/blog/filtering-undefined-elements-from-array-typescript/
/*
* Let's say I have a list of MyObjects and I want to filter down to all of the contained MySubProperties.
*
* I need to filter out the objects with undefined property values since they cannot have a subproperty, and
* I need TypeScript to understand that the result type of that filter is MyProperty[] rather than
* (MyProperty | undefined)[] - that way, ts won't flag the access of p.subProperty for possibly undefined values.
*/
interface MyProperty {
subProperty: string;
}
interface MyObject {
property?: MyProperty;
}
const myObjects:MyObject[] = [...someObjects];
const mySubProperties = myObjects
.map(o => o.property)
.filter((property): property is MyProperty => !!property)
.map(p => p.subProperty);
/* Some things to note, per the site referenced above:
- `!!property` returns true if property is not falsey (false, 0, null, undefined)
- The `property is MyProperty` return type guarantees a boolean return value for the filter
- The above factors allow TypeScript to infer the return type of this filter as MyProperty[] so that
the following call to `.map` does not show any "possibly-undefined" ts errors when accessing `p.subProperty`
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment