Skip to content

Instantly share code, notes, and snippets.

@tuliren
Last active July 18, 2023 23:25
Show Gist options
  • Save tuliren/5262597ee359e104f34db38e5db8a823 to your computer and use it in GitHub Desktop.
Save tuliren/5262597ee359e104f34db38e5db8a823 to your computer and use it in GitHub Desktop.
Partial Type Predicate in TypeScript
interface Base {
base1: string;
base2: string;
a: string;
}
interface Interface1 extends Base {
b: number;
}
interface Interface2 extends Base {
c: boolean;
}
type UnionInterface = Interface1 | Interface2;
/**
* When the input is a partial object, the type predicate must also be a partial check.
*/
const isI1 = (i: Omit<UnionInterface, 'base1'>): i is Omit<Interface1, 'base1'> => (i as Interface1).b != null;
function fn({base1, ...params}: UnionInterface): void {
if (isI1(params)) {
console.log(params.b);
} else {
console.log(params.c);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment