I'm not sure if the title describes my situation properly so I'd appreciate any edits in case there's a better way to phrase it.
I have a helper function that takes in a Database model and allows for the searching of rows in the Database table that belongs to the model.
It can be simplified as having three parameters, the database model, a search phrase, and the fields (columns) in which to look for the search phrase.
Right now I'm using a generic type called ModelAttributes in order to dynamically determine which fields are allowed to be passed to the fields property of the search function like so:
type ModelAttributes<SpecificModel> = {
// First filter only keys that are strings
[Field in keyof SpecificModel]: SpecificModel[Field] extends string
? // Of the string based keys, if they are generic to the Model type ignore them
Field extends keyof Model
? never
: Field
: never;
}[keyof SpecificModel];
type SmartSearchParams<SpecificModel extends StandardModel> = {
search: string;
model: SpecificModel;
fields: ModelAttributes<SpecificModel>[];
};
The problem is that I want the function to also have another parameter called associatedModels of the following type:
type AssociatedQueryTypes<AssociatedModel> = {
model: AssociatedModel,
fields: ModelAttributes<AssociatedModel>
}
Now you can pass a parameter called associatedModels with an array of the AssciatedQueryTypes and it should also validate that any fields used there belong to the model that was passed alongside it as well.
The problem arises because I don't know how to properly add the new type to the SmartSearchParams type.
I've tried the following:
type SmartSearchParams<SpecificModel extends StandardModel> = {
search: string;
model: SpecificModel;
fields: ModelAttributes<SpecificModel>[];
associatedModels: AssociatedQueryTypes<any>[]; // The 'any' is a problem
};
Now when I try to use the function it doesn't actually validate that the fields in the associatedModels parameter belong to the model that was passed alongside it, likely because of the any keyword. Is there any way around this?