'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:
- should not be allowed to pass
metastring asTKey - 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
Solution 1:[1]
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,
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Emma Koskinen |
