Home > Software engineering >  Multiple types with just one object key difference - is there a way to make them generic?
Multiple types with just one object key difference - is there a way to make them generic?

Time:04-07

I have multiple methods that are almost the same, they just have one different key in their return types. Is there some way to make them generic, so that I only need to enter key name into the generic type?

type IsUsersModuleLockedReturnType = {
  isLocked: true,
  usersRestriction: Restriction
} | {
  isLocked: false,
  usersRestriction: null
}

// This type is almost the same as above, but uses different key for restriction. Can I somehow make it generic?
type IsGroupsModuleLockedReturnType = {
  isLocked: true,
  groupsRestriction: Restriction
} | {
  isLocked: false,
  groupsRestriction: null
}

The best case for me would be if the key is inferred from the method itself, but I don't know how to do that.

public readonly getIsUsersModuleLocked = (): IsUsersModuleLockedReturnType => {
    if ('users' in this.restrictions) {
      return {
        isLocked:true,
        usersRestriction: this.restrictions.users 
      }
    } else {
      return {
        isLocked: false,
        usersRestriction: null
      }
    }
  }

Typescript playground link

CodePudding user response:

You can do that with Mapped Types

In your case you could do it like:

type genericType<T extends string> = ( { isLocked: true } & { [key in T]: Restriction } ) 
| ( {isLocked: false} & {[key in T]: null} );

type IsUsersModuleLockedReturnType = genericType<"usersRestriction">;
  • Related