Currently, I am working on a method in Typescript that is responsible for extracting allowable property types from an object of a constrained generic type.
The scenario involves a type called ParticipantBase
which consists of properties like
first: string, last: string, extras: [key: string]: string
. To accomplish this task, I have developed a function named getAllowedEntry
, which takes an object of type ParticipantBase along with a key where the value in the ParticipantBase object corresponds to the type AllowableType. This setup is functioning correctly.
However, my goal is to enhance this function by incorporating generics. Unfortunately, when I integrate generics into the equation, errors start creeping up, and it appears that the Typescript compiler can no longer ensure the typings.
I believe there may be a fundamental aspect regarding typings and generics in TypeScript that eludes me. If someone could provide assistance or insights in this matter, I would greatly appreciate it.
For reference, a minimal sample code snippet (also accessible in playground) has been provided:
type PropertiesOfType<U, V> = {
[P in keyof U]: U[P] extends V ? P : never;
}[keyof U];
type AllowedPropertyTypes = string | number;
type ParticipantBase = {
first: string;
last: string;
extras: { [property: string]: string };
};
// Does not work.
function getAllowedEntry<T, K extends PropertiesOfType<T, AllowedPropertyTypes>>(participant: T, key: K): AllowedPropertyTypes {
return participant[key];
}
// Functions perfectly fine.
function getAllowedParticipantEntry<K extends PropertiesOfType<ParticipantBase, AllowedPropertyTypes>>(participant: ParticipantBase, key: K): AllowedPropertyTypes {
return participant[key];
}