score:4

Accepted answer

I bet that this is the result You want to achieve

type Person = {
    name: string,
    age: number
};

export const usePerson = function <T extends Person>() {
    const setPersonProperty = <K extends keyof T> (property: K, setter: (value: T[K]) => T[K]): void => {
        console.log(property, setter)
    }

    setPersonProperty("name", (x) => x)

    return setPersonProperty;
}

 const setPerson = usePerson<Person>()

 setPerson("name", (name) => name)

Basically, in code you provided there are two generic types when calling this usePerson hook T and K (<T extends Person, K extends keyof T>).

Let's say someone will call this function with usePerson<Person, "age">(). What typescript will do it will replace types inside our usePerson to be T = Person and K = "age"

And now you have a mismatch since setPersonProperty have first argument of type K ("age") the argument "name" is not assignable - that the error you see.


Related Query

More Query from same tag