Last active
April 23, 2021 01:14
-
-
Save kliph/52548e387e6997710efba0aaa0c79a05 to your computer and use it in GitHub Desktop.
Narrowing types with predicates
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
const A_TYPE = "a"; | |
const B_TYPE = "b"; | |
type AProps = { | |
type: typeof A_TYPE; | |
foo: string; | |
bar: number; | |
}; | |
type BProps = { | |
type: typeof B_TYPE; | |
foo: number; | |
frob: string; | |
}; | |
type AllProps = AProps | BProps; | |
const fn = ({ foo, type }: AllProps) => { | |
if (type === A_TYPE) { | |
return foo; | |
} | |
}; | |
const isA = (props: AllProps): props is AProps => { | |
return props.type === A_TYPE; | |
}; | |
const fn2 = (props: AllProps) => { | |
if (isA(props)) { | |
return props.foo; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment