Typescript error: Type 'K' cannot be used to index type’T'

Asked

Viewed 219 times

1

I’m starting with Typescript and I stalled at the time of typing the following function:

const pickProp = prop => obj => obj[prop]

I’m trying this way:

const pickProp = <K>(prop: K) => <T extends { [K in keyof T]: any }>(obj: T) => obj[prop]

And I’m getting the following mistake:

Type 'K' cannot be used to index type 'T'.

How would it be possible to type the function pickProp?

1 answer

1


Jmedeiros, this site is for Portuguese questions only.

If I understand your code intuition correctly, you are trying to create a function that takes the name of a property, and returns another function to capture the value of that property of the objects passed to it, correct?

What you are trying to do can be obtained with the following code:

function pickProp<T extends string | number | symbol>(prop: T) {
    return function<V extends {[key in T]: any}>(obj: V) {
        return obj[prop]
    }
}

Note that K (or key) is not one of the values of keyof T, K is a value of T, for T is property itself, not an object.

I also needed to ensure that T must be the type string, number or symbol, because these are the types of properties valid for an object, otherwise the generic object {[key in T]: any} would not be valid,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.