I want to define a Person type, as such:
interface Person {
gender: 'male'|'female';
pants?: string;
skirt?: string;
}
However, I want to make it more specific, whenever the gender=male, then pants must exist, or if gender=female, then skirt must exist, something like this:
interface Person { Person {
gender: 'male'; [OR] gender: 'female';
pants: string; skirt: string;
} }
Both are similar object, except have few keys different. Is it possible? Is this a good practice in typing an object?
I hope I can do something like:
interface Person {
gender: 'male'|'female'|'elf'|'undead';
head?: string;
pants?: string exists if gender='male';
skirt?: string exists if gender='female';
leg?: string;
tail?: string exists if gender='elf'|'undead';
}
Haha... Probably I think too much...
interface MalePerson extends Personorinterface FemalePerson extends Person?sub-interface, then my.tsfile will full withimportinterface statement... Hmmm...extendsand applyindex.tsimport... thanks everyone...genderis the discriminant. Is there something about that solution which wouldn't work for you? (And if so, can you add detail to the question?)