I have dedicated quite a bit of time to this task and would greatly appreciate some assistance. I am in need of a component (a function) that can accept an array of objects while also validating the properties of these objects.
Here are the interfaces and data structures:
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', // only allows 'label' or 'id' 👍
}
const fruitMeta: TableMeta<Fruit> = {
data: [],
searchKey: 'name', // only allows 'name' or 'id' 👍
onClick: (item) => {item.id} // ✔️ has correct item type <---------------
}
const metas = [vegetableMeta, fruitMeta];
Now, let's look at a component (which is essentially a function):
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 specific structure of objects within the array cannot be predetermined
Any suggestions on how we can make this work?