0

Let's say I have this:

type KeyForValueType<T, ValueType> = { [K in keyof T]: T[K] extends ValueType ? K : never; }[keyof T];

declare function fn1<T, ValueType>(obj: T, key: KeyForValueType<T, ValueType>): void;

fn1 will work as expected, it will properly limit the key I can use based on the type of value of that key:

fn1<{ a: number; b: string }, string>({ a: 11, b: 'str' }, 'a'); // error as expected
fn1<{ a: number; b: string }, string>({ a: 11, b: 'str' }, 'b'); // works
fn1<{ a: number; b: string }, number>({ a: 11, b: 'str' }, 'a'); // works
fn1<{ a: number; b: string }, number>({ a: 11, b: 'str' }, 'b'); // error as expected

I got the above from here: https://stackoverflow.com/a/51476941/520229

However, when actually implementing the function, I am unable to get it to recognize the type of the value:

// with generic ValueType
function fn2<T, ValueType>(obj: T, key: KeyForValueType<T, ValueType>): void {
  const value: ValueType = obj[key];
  console.log(value);
}

// or even fixed value type
function fn3<T>(obj: T, key: KeyForValueType<T, string>): void {
  const value: string = obj[key];
  console.log(value);
}

Check it out here.

Am I doing something wrong here? Is this even possible to do with typescript?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
mrzli
  • 16,799
  • 4
  • 38
  • 45
  • Possible duplicate of [TypeScript: Accept all Object keys that map to a specific type](https://stackoverflow.com/questions/61764867/typescript-accept-all-object-keys-that-map-to-a-specific-type) – jcalz May 24 '20 at 03:51
  • @jcalz Thx, you are right. Actually my solution even had some additional problems, but the one you provided worked. Voting to close. – mrzli May 24 '20 at 20:53

0 Answers0