I have the following piece of code
// Address and User are two classes, bothe of which have an id
type Q = Address | User
// This works just fine
async function c<EntityType = Q>(ids: Q["id"][]) {
}
// This gives me the error described bellow
async function c<EntityType = Q>(ids: EntityType["id"][]) {
}
The problem I get if I use the second function definition is:
Type '"id"' cannot be used to index type 'EntityType'
Further when I in vscode hover over ids in the first function I get (parameter) ids: number[] (Which is expected as Q.id is a number) but if I hover over ids in the second function I get ids: EntityType["id"][]
How can I fix this problem??
c<{hello: string}>(someArray)will not work with the second definition. Or evenc<string>(someArray). Remember that it's the caller who determines the generic type argument. You cannot assume that it will be any specific thing when you have not constrained it.EntityTypein the second case. You still just need to constrain it withextends. It's basically the same problem. Just different manifestation.Qa union of your classes, makeQan inferface which includesid: numberas a property and have your classes implementQ.