I am currently working on creating a versatile function where the generic type is used to define its parameter.
Here's an excerpt from this parameter :
type Configuration<T> = {
masterdata: T[],
target: ????
}
I am encountering difficulties in typing the target
property. I want it to be the name of any property within a specific class (MtmFormComponent
, the current class) but with the condition that the property type is T[]
.
The purpose is to write :
this[configuration.target] = configuration.masterdata;
.
I have made progress, and here is how I have typed the target
property so far:
type MtmFormComponentPropertyOfType<T, K extends keyof MtmFormComponent> = MtmFormComponent[K] extends T[] ? K : never;
type DropdownAutocompleteConfiguration<T, K extends keyof MtmFormComponent> = {
masterdata: T[],
targetFilteredList: MtmFormComponentPropertyOfType<T, K>,
};
Everything works well when declaring an object of type
DropdownAutocompleteConfiguration
, as my IDE correctly guides me to use only a key that leads to the same type as the value of masterdata
. Therefore, it seems like my type is accurately defined.
The issue arises when using this object in my generic function:
private setupDropdownAutocompleteBehaviour<T, K extends keyof MtmFormComponent>(configuration: DropdownAutocompleteConfiguration<T, K>): void {
this[configuration.targetFilteredList] = configuration.masterdata;
// ...
}
In this case, the
this[configuration.targetFilteredList]
expression triggers the following error:
Type 'T[]' is not assignable to type 'this[Currency[] extends T[] ? "filteredCurrencyList" : never] & this[PriceUnit[] extends T[] ? "filteredPriceUnits" : never] & this[Subscription[] extends T[] ? "subscriptions" : never]'.
Type 'T[]' is not assignable to type 'this[Currency[] extends T[] ? "filteredCurrencyList" : never]'.
Type 'T[]' is not assignable to type 'Currency[]'.
Type 'T' is not assignable to type 'Currency'.
My understanding is that while inside the function, TypeScript fully resolves the type of
this[configuration.targetFilteredList]
rather than recognizing it as T[]
. Despite the auto-complete feature in my IDE, I am certain that a value for target
won't lead to a type incompatible with the one specified for masterdata
.
At this point, I'm unsure about what steps to take next :/
Appreciate your assistance :)