Reputation: 16716
Suppose I want to type an object where I don't know the name of one of properties, but know the type of its value. So it's something like that:
type PagedResponse<T> = {
Suppliers: Array<T>; // <- this prop might have different name
nextPageToken: number;
total: number;
};
Suppliers
prop might be of different name - Products
or anything else, but it should be of type Array<T>
. How do I type something like that? Is it possible to pass the name of that last prop as another argument to the type.
Upvotes: 0
Views: 72
Reputation: 80
You can do something like this
type PagedResponse<T> = {
[prop: string]: Array<T>; // <- this prop might have different name
nextPageToken: number;
total: number;
};
Upvotes: 1
Reputation: 25790
Try this:
type PagedResponse<T, K extends string = string> = {
nextPageToken: number;
total: number;
} & {
[P in K]: Array<T>;
}
const response: PagedResponse<number, 'Products'> = {
Products: [1, 2, 3],
total: 10,
nextPageToken: 20
}
Upvotes: 1