Repository navigation
Generics: Cannot limit template param to specific types #20235
Description
Generics currently allow you to restrict the type of a template param to any type that extends some type, but as far as I know, there's no way to restrict the type of the template param to specific types.
For example, I'm trying to create a generic type where the template param is one of any specific type in a discriminated union, but the compiler doesn't treat the type as a discriminated union within generic code. Here's is a super simplified example:
interface Cat {
type: "cat"
meow(): void;
}
interface Fish {
type: "fish"
swim(): void;
}
// discriminated union
type Animal = Cat | Fish;
// template param should really be limited to exactly Animal (Cat or Fish)
interface AnimalWrapper<T extends Animal> {
animal: T;
}
function foo<T extends Animal>(animalWrapper: AnimalWrapper<T>) {
if (animalWrapper.animal.type === "cat") {
// ERROR: Property 'meow' does not exist on type 'T'
animalWrapper.animal.meow()
} else {
// ERROR: Property 'swim' does not exist on type 'T'
animalWrapper.animal.swim()
}
}Is it reasonable to expect that my code example should work, and that this is a bug? Or is there some technicality about T extending Animal rather than being Animal that prevents the compiler from making the typical assumptions that would allow my code example to work?
On the surface, it's hard for me to imagine how anything could possibly extend Animal, and have any value for type other than "cat" or "fish". Shouldn't the compiler be able to determine in my "if cat" statement that animalWrapper.animal is indeed something that extends Cat, and therefore must have the "meow" method?
Would it be reasonable to expand the syntax of Generics to be able to limit the template param to specific types? Here's what I imagine:
// "is" would indicate that "T" must be exactly one of the types in the "Animal" union.
// Or maybe it would make more sense to use "in" instead of "is"?
interface AnimalWrapper<T is Animal> {
animal: T;
}
function foo<T is Animal>(animalWrapper: AnimalWrapper<T>) {
// Now that "T" is limited specifically to Cat or Fish, the following code should be valid
if (animalWrapper.animal.type === "cat") {
// Compiler should now know BOTH:
// 1) animalWrapper.animal is of type 'Cat'
// 2) animalWrapper is of type AnimalWrapper<Cat>
animalWrapper.animal.meow()
} else {
animalWrapper.animal.swim()
}
}
Activity
Proculopsis commentedon Nov 23, 2017
Here is a workaround in the Playground: https://goo.gl/u3tUDW
UselessPickles commentedon Nov 23, 2017
Proculopsis Your "foo" function is only working because it is not using the template type:
If you change the method signature to
animal: T, then you get a compiler error atanimal.swim().Proculopsis commentedon Nov 23, 2017
Here is another attempt in the Playground: https://goo.gl/grTLZ1
Sorry, I tried to simplify your example - the above implements AnimalWrapper and includes isFish() because the transpiler doesn't know that isCat()/else is exhaustive.
UselessPickles commentedon Nov 23, 2017
Yeah, I'm basically doing the same thing - using custom type guards to force the compiler to know what type it is wherever necessary.
One problem with this workaround is that you lose the ability to test against "never" to guarantee that all possible cases have been covered by the code:
RyanCavanaugh commentedon Aug 7, 2018
This is effectively what generics already are? There's another proposal floating around for upper-bounded generics which may be what you want, but it's hard to tell.
It's hard to speak to this issue specifically because the type parameter isn't really doing anything in the example. In most cases where you actually use the type parameter in a way that accomplishes something (correlating two parameters, two properties in the same parameter, or a parameter to a return type) it can be rewritten in a way that works the way you expect while still doing the right thing.
The salient thing to mention is that we can't safely say that the type of
AnimalWrapper<T extends Animal>.animalis actuallyCateven if itstypeis"cat"! You could have anAnimalWrapper<FancyCat>, at which point it would be unsound to allow you to assign a non-Fancycat to the.animalproperty.UselessPickles commentedon Aug 8, 2018
Ryan Cavanaugh (@RyanCavanaugh) Actual use cases I have are more complex and make use of the type parameter more extensively, but this example is simplified to point out specifically the issue I experienced with expecting the discriminated union type
Animalto "work" as a type parameter, such that type narrowing would happen when testing the discriminator.Your example of a
FancyCatwould have to be assignable to eitherDogorCat(probablyCat), so I would still expect the compiler to understand that ifanimalWrapper.animal.type === "cat", thenanimalWrapper.animalmust have the properties defined in theCatinterface.UselessPickles commentedon Aug 8, 2018
I see what you mean now about assigning a wrong type to
animalWrapper.animal.I think this is part of why I was suggesting some way to limit the generic type param to EXACTLY the
Animaltype union, rather than anything that is assignable toAnimal. But I understand that everything in the type system is about assignability of "shapes" of types, rather that exact types themselves, so that's probably never going to happen.So maybe ignore my suggested solution and just look at my problem: why can't the compiler figure out that that the
meow()method exists onanimalWrapper.animalafter testing thatanimalWrapper.animal.type === "cat"? Can this problem be solved somehow within the design of the type system?sstokker-yopeso commentedon May 1, 2020
Jeff Lau (@UselessPickles) a bit of a late reply, but recently I came across a very similar problem, and someone suggested doing this, whenever the TS compiler can't distinguish between union-types -- worked like a charm for me: