cl0udw4lk3r
cl0udw4lk3r

Reputation: 2733

Generic object type with a dynamic key

I want to achieve a generic type that will have a parametric key, like that (not valid TS example):

type PaginatedData<TKey, TData> = {
  [TKey]: Array<TData>
  meta?: {
    limit: number
    offset: number
  }
}

Ideally the requisites are:

  1. should not be allowed to pass meta string as TKey
  2. the key of the array items should be generic I need to pass it from the outside..

I've already tried with:

type PaginatedData<TKey extends string, TData> = {
 [key in TKey]: Array<TData>
} & {meta?: {limit: number, offset: number}}

But it breaks the 1. constraint

Upvotes: 1

Views: 432

Answers (1)

Emma
Emma

Reputation: 855

Unfortunately I can't explain why your example doesn't work, but a solution would be to make a union of Record and an object type:

type PaginatedData<TKey extends string, TData> =
    Record<TKey, TData[]> & {
        meta?: {
            limit: number,
            offset: number,
        }
    };

const page: PaginatedData<"p0" | "p1" | "p2", number> = {
    p0: [0],
    p1: [1],
    p2: [2],
    meta: {
        limit: 100,
        offset: 100,
    }
}

Link to a playground

Upvotes: 1

Related Questions