Is there a way to make a generic T extend either type1
or type2
in TypeScript?
For example, I have the following:
interface Edible { }
interface Fruit extends Edible {
isFruity: boolean
}
interface Veggie extends Edible {
isHealthy: boolean;
}
interface Dairy extends Edible {
isHighProtein: boolean;
}
interface Apple extends Fruit {
nice: boolean;
sweet: boolean;
}
// and so on so forth...
Now I want to have a function that takes in something that's either a Fruit
or Veggie
, how do I make it happen? Is this the right way to express "extend either Fruit
or Veggie
" at all?
function yum<T extends Fruit | Veggie>(thing: T) {
//...
if ("isFruity" in thing) {
thing.isFruity; // Error: Property 'isFruity' does not exist on type 'T'.
}
}
Further more, how to narrow down the type even further to Apple
, for example?
function yum<T extends Fruit | Veggie>(thing: T) {
//...
if ("isFruity" in thing) {
thing.isFruity; // Error: Property 'isFruity' does not exist on type 'T'.
if ("sweet" in thing) {
console.log("this is an apple!");
thing.sweet; // Error: Property 'sweet' does not exist on type 'T'.
}
}
}