0

I wan't to do some type mapping with function parameters as belows:

interface TestType {
  something: string;
  other: number;
}

function func<T, K extends keyof T = keyof T>(key: K, arg: T[K]) {  // Here didn't work
  // do something
}

// func<TestType>( should auto complete with 'something' or 'other', and arg should be the right type

The func generic type didn't do the right type mapping, how to define func type so that func<TestType> can auto complete with 'something' or 'other', and arg should be the right type? (something -> string, other -> number)

Playground

2
  • You cant declare one generic parameter and infer the other, it's either both inferred or both declared. I'll either find an existing answer or explain this myself later, but this is usually solved by using an intermediate function like this: tsplay.dev/w2Pgjm Commented Jul 5, 2022 at 4:07
  • @AlexWayne I got it. The existing question has explained this and the workaround is the same as yours. Also I think typescript should do this easier. Thank you for your answer. Commented Jul 5, 2022 at 8:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.