Last active
September 5, 2023 10:37
-
-
Save andreievg/f9ae20bc4dc49b3d7862380fe1d8141b to your computer and use it in GitHub Desktop.
A method to narrow down an array of discriminated unions
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Kudos to this stack overflow post.
.filter
would also work