Reputation: 2733
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:
meta
string as TKey
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
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,
}
}
Upvotes: 1