2

I have the following function:

function prop<T extends Record<any, any>, K extends keyof T>(key: K): T[K] {
   
}

const v = prop<{ test: string }>('test')

The issue is that I must pass a second generic to correctly infer the key. Is there any way to skip the second generic and still infer the key as keyof T?

I don't want to do the following:

prop<{ test: string }, 'test'>('test')

1 Answer 1

1

You could try to use default generic like this one:

function prop<T extends Record<any, any>, K = keyof T>(key: K): T[K] {
   
}

const v1 = prop<{ test: string }>('test') // OK
const v2 = prop<{ test: string }>('test12') // ERROR
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.