Home > Net >  TypeScript uility type to convert all key types into arrays of that key type
TypeScript uility type to convert all key types into arrays of that key type

Time:07-30

I have an interface (type) defined as

 interface User {
     name: string,
     id: string,
     age: number,
     town: string
 }

I now have a function which will search for Users which match a particular field or fields. I don't want to have to manually declare another type UserFilter, e.g.:

 interface UserFilter {
     name: string[],
     id: string[],
     age: number[],
     town: string[]
 }

To be able to do

function findUsers(filter: Partial<UserFilter>) {
   if (filter.id) {
    mySQLQueryBuilder.whereIn('id', filter.id)
   }
   ...
}

Basically in User every key was a scalar and in UserFilter it is now an array of the same type.

I feel that having to create a separate type (UserFilter), which is so similar to User, is wasteful and more surface area for bugs/maintaince.

Ideally I'd like to be able to use TypeScript's (utility?) types to basically convert the User type's fields into arrays of the same type (I call this ConvertAllKeysToArrays)

function findUsers(filter: Partial<ConvertAllKeysToArrays<User>>) {
   if (filter.id) {
    mySQLQueryBuilder.whereIn('id', filter.id)
   }
   ...
}

Thanks

CodePudding user response:

There is no existing utility type for this, but we can use mapped types to make our own.

type MapToArrays<T> = {
    [K in keyof T]: T[K][]
}

type UserFilter = MapToArrays<User>

Playground

  • Related