Home > Back-end >  Pass a primitive as a generic parameter in order to use it as an object key
Pass a primitive as a generic parameter in order to use it as an object key

Time:09-02

In my object, I have two properties, one of which is hardcoded and the second one has to be dynamic. How can I pass the desired key name in generic type so that it yields a type with that key?

Example:

interface Pagination<key, Content> {
  pagination: {
      total: number;
      page: number;
  },
  `${key}`: Content[];
}

// expected behavior
type ProductData = Pagination<'products', Product>;
const productResponse: ProductData = {
  pagination: {...},
  products: [...],
}

CodePudding user response:

You can convert Pagination to a type and intersect it with a mapped type containing only a single key. The generic type Key also needs a constraint which can either be string, number or symbol or a union of those.

type Pagination<Key extends string, Content> = {
  pagination: {
      total: number;
      page: number;
  },
} & {
  [K in Key]: Content[];
}

Playground

  • Related