Below is the code snippet I am currently working with:
type AlphaNumeric = string | number | null | boolean | undefined;
type AlphaNumericKeys<T> = {
[key in keyof T]: key extends string ? (T[key] extends AlphaNumeric ? key : never) : never;
}[keyof T];
This code functions effectively by providing all keys of a generic object T that have values fitting the AlphaNumeric criteria (which I use for sorting arrays based on specific keys).
For instance, considering a person object, the AlphaNumeric keys would be as follows:
type Person = {
name: string;
age: number;
friends: Person[];
doSomething: Function;
}
type PersonAlphaNumericKeys = AlphaNumericKeys<Person> // "name" | "age"
While this setup works flawlessly up to this point, an issue arises when using these keys on object T.
type AlphaNumericValuesOfPerson = Person[AlphaNumericKeys<Person>] // string | number
Although it seems logical initially, things tend to break down when incorporating generics.
type SomeValues<T> = T[AlphaNumericKeys<T>] // T[AlphaNumericKeys<T>], rather than just AlphaNumeric as anticipated.
I am seeking a solution to make T[AlphaNumericKeys] possess the same type or at least be assignable to AlphaNumeric. This way, if there is a function that requires AlphaNumeric input, passing T[AlphaNumericKeys] should work seamlessly.