Skip to content

Instantly share code, notes, and snippets.

@kliph
Last active April 23, 2021 01:14
Show Gist options
  • Save kliph/52548e387e6997710efba0aaa0c79a05 to your computer and use it in GitHub Desktop.
Save kliph/52548e387e6997710efba0aaa0c79a05 to your computer and use it in GitHub Desktop.
Narrowing types with predicates
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