sev
sev

Reputation: 1822

Typescript passes type differently to function when using generic

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

Upvotes: 0

Views: 23

Answers (1)

Dylan Dang
Dylan Dang

Reputation: 166

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"][]) {
}

Upvotes: 1

Related Questions