Joji
Joji

Reputation: 5613

TypeScript: How can I explicitly pass in the type to the generics for this function

I am learning TypeScript and I was trying to use mapped types to write a function that only allows users to extract values off of the object when the keys indeed exist on the object. Here is the code

const obj = {
    a: 1,
    b: 2,
    c: 3
}

function getValues<T, K extends keyof T>(obj: T, keys: K[]) {
    return keys.map(key => obj[key])
}

getValues(obj, ['a', 'b'])

So here I defined two type parameters T and K and they are inferred by the TS compiler because when I called the function I didn't explicitly pass in the types.

Now my question is, what if I want to explictly pass the types into the function, how should I rewrite the function? I want to do this because I am curious about how the type inference works here

so this is my attempt

getValues<typeof obj, string[] extends keyof typeof obj>(obj, ['a'])

However the compiler is not happy. There is an parsing error Parsing error: '?' expected

Upvotes: 0

Views: 224

Answers (1)

codemax
codemax

Reputation: 1352

Assuming you really want to pass a type in explicitly, I don't think using extends is allowed in the invocation of the function.

getValues<typeof obj, keyof typeof obj>(obj, ['a'])

Upvotes: 1

Related Questions