0

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??

5
  • A call like c<{hello: string}>(someArray) will not work with the second definition. Or even c<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. Commented Oct 11, 2022 at 20:08
  • @VLAZ would you mind elaborating how I could constrain this in my related post here stackoverflow.com/questions/74033593/…? It seems I made a wrong assumption in the post above which Dylan picked up on Commented Oct 11, 2022 at 20:11
  • It's exactly the same answer. You still have unconstrained EntityType in the second case. You still just need to constrain it with extends. It's basically the same problem. Just different manifestation. Commented Oct 11, 2022 at 20:13
  • Sorry copy paste error - I fixed it now Commented Oct 11, 2022 at 20:14
  • a good practice that might help is instead of making Q a union of your classes, make Q an inferface which includes id: number as a property and have your classes implement Q. Commented Oct 11, 2022 at 20:17

1 Answer 1

1

Although you set the generic to type Q by default, the generic could still be any. To fix this, you need to limit the type of the generic by using the extends keyword like so:

async function c<EntityType extends Q>(ids: EntityType["id"][]) {
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.