I spent quite some time on this and I would appreciate some help. I want a component (a function) to accept an array of objects while also validating the properties of the objects.
Interfaces and data:
interface ObjectWithId {
id: string | number;
}
interface TableMeta<T extends ObjectWithId, K extends PropertyKey = keyof T> {
data: T[];
searchKey: K;
onClick?: (item: T) => void;
}
interface Vegetable {
id: number,
label: string,
}
interface Fruit {
id: number,
name: string,
}
const vegetableMeta: TableMeta<Vegetable> = {
data: [],
searchKey: 'label', // this only allows 'label' or 'id'
}
const fruitMeta: TableMeta<Fruit> = {
data: [],
searchKey: 'name', // this only allows 'name' or 'id'
onClick: (item) => {item.id} // ✔️ has correct item type <---------------
}
const metas = [vegetableMeta, fruitMeta];
A component (a function for simplicity):
const metaParser = (metas: TableMeta<{id: number | string}, PropertyKey>[]) => {
const id = metas[0].data[0].id; // should be `number | string`
}
metaParser(metas); // ❌ Type 'ObjectWithId' is not assignable to type 'Vegetable'
The shape of objects in the array is unknown in advance
Any ideas on how to make it work?