Last active
July 18, 2023 23:25
-
-
Save tuliren/5262597ee359e104f34db38e5db8a823 to your computer and use it in GitHub Desktop.
Partial Type Predicate in TypeScript
This file contains hidden or 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
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