Issue
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: [...],
}
Solution
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[];
}
Answered By - Tobias S.
 
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.