Generic constraints with a union type

There is some room for using a union in the extends clause of a generic definition. While you cannot use discriminator, you can compare against an array. The following object allows a type and an array of the same type. You can narrow down to any of the two types using instanceOf and manipulate the parameter value:

interface ObjectWithAge {
kind: "ObjectWithAge";
age: number;
}

function funct2<T extends ObjectWithAge | ObjectWithAge[]>(p: T): T {
if (p instanceof Array) {
return p[0];
}
return p;
}

Trying to extend two different objects with a discriminator does not work at the moment.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.110.86