'Is it possible to use a property whose type is specified in Generics in a function?

const func = <T extends object, S extends keyof PickByValue<T, string>>(
  obj: T,
  key: S
): string => {
  return obj[key];
};

PickByValue extracts the properties of T whose values are of type string.

type T = {
  propStr: string;
  propNum: number;
}
type Bar = PickByValue<T, string>;
// Bar = {
//   propStr: string;
// }

Is it possible to create a PickByValue such that the above code does not result in an error?

What we want to do is to use a property of type string within obj in a function.



Solution 1:[1]

May 6th - TypeScript 4.6.2

You can do this by a generic constraint referencing T:

const func = <T extends PickByValue<T, string>, S extends keyof PickByValue<T, string>>(
  obj: T,
  key: S
): string => {
  return obj[key];
};

This is similar in behaviour to this question.

And when you call it, it works fine:

const obj = {
    foo: 0,
    bar: "",
    baz: "",
    quz: false,
};

// no errors
func(obj, "bar"); // intellisense for the keys that point to strings

Playground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hittingonme