Skip to content

Instantly share code, notes, and snippets.

@andreievg
Last active September 5, 2023 10:37
Show Gist options
  • Save andreievg/f9ae20bc4dc49b3d7862380fe1d8141b to your computer and use it in GitHub Desktop.
Save andreievg/f9ae20bc4dc49b3d7862380fe1d8141b to your computer and use it in GitHub Desktop.
A method to narrow down an array of discriminated unions
type One = { one: 'one'; t: 'one' }
type Two = { two: 2; t: 'two' }
type OneOrTwo = One | Two
const rows: OneOrTwo[] = []
const getOneOrTwo = <T extends OneOrTwo['t']>(t: T) => {
return rows.find((obj): obj is Extract<OneOrTwo, {t: T}> => obj.t === t)
}
let one = getOneOrTwo('one')
if (one) {
one.one == 'one'
}
let two = getOneOrTwo('two')
if (two) {
two.two == 2
}
@andreievg
Copy link
Author

andreievg commented Sep 5, 2023

Kudos to this stack overflow post.

.filter would also work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment