My interface (type) is currently defined as:
interface User {
name: string,
id: string,
age: number,
town: string
}
I have a function now that will search for Users based on specific fields. I prefer not to manually declare an additional type UserFilter like this:
interface UserFilter {
name: string[],
id: string[],
age: number[],
town: string[]
}
Instead, I wish to achieve the following functionality:
function findUsers(filter: Partial<UserFilter>) {
if (filter.id) {
mySQLQueryBuilder.whereIn('id', filter.id)
}
...
}
The idea is to have each key in User represented as a scalar and in UserFilter as an array of the same type.
I believe creating a separate type like UserFilter, which is so similar to User, adds unnecessary complexity and potential for errors during maintenance.
My ideal solution would involve using TypeScript's utility types to automatically convert the fields of the User
type into arrays of the same type. I'd call this transformation ConvertAllKeysToArrays
.
function findUsers(filter: Partial<ConvertAllKeysToArrays<User>>) {
if (filter.id) {
mySQLQueryBuilder.whereIn('id', filter.id)
}
...
}
Thank you