I have a straightforward scenario in mind. I am looking to create a function called pluckOnlyStringValues
that takes an object obj
and a key
. The main requirement is that the key passed should correspond to a string value in the object, ensuring that pluckOnlyStringValues
always returns a string
.
To achieve this, I attempted to implement a type helper called PickKeysByValue
, but unfortunately, it seems to be facing some challenges...
type PickKeysByValue<T extends object, ValueTypes> = {
[K in keyof T]-?: T[K] extends ValueTypes ? K : never;
}[keyof T];
// Successful examples
type GetKeysWithStringValues = PickKeysByValue<
{ a: string; b?: string; c: number | undefined; d: () => 4 },
string
>;
type GetStringValues = { a: string; b?: string; c: number | undefined; d: () => 4 }[GetKeysWithStringValues]
// Trouble encountered
const pluckOnlyStringValues = <O extends { a: string }>(
obj: O,
key: PickKeysByValue<O, string>,
): string => {
return obj[key];
};