Typescript use optional generic

Viewed 52

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 Answers

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
Related