-1

My issue is similar to the one described here and here (and probably other places too). I feel like it's a simple Lookup Type issue (documented here). But my use case is slightly different and I cannot get it to work.

I have a function that takes an object of Type and returns a "getter" function for this object. Here's a simple playground.

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

const makeGetter = <Type, Key extends keyof Type>(obj: Type) => (key: Key) => obj[key];

const user: User = {
    age: 55,
    name: 'Brian',
};

const getter = makeGetter(user);
const u = getter('age');

However, the selected property is always a union of all possible property types.

What am I missing?

1 Answer 1

1

The problem is that your generic will be created on creation of the makeGetter function. At this time Keyisn't resolved to a specific key yet. Move the generic to the curried function.

const makeGetter = <Type extends Object>(obj: Type) => <K extends keyof Type>(key: K) => obj[key]

Playground

Sign up to request clarification or add additional context in comments.

1 Comment

After meddling with it for a while longer, I reached the same conclusion as well. This way it indeed works.

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.