I'm creating a simple schema-like type to dynamically generate tables using React.
Those are the types that I wrote:
type MySchemaField<T, K extends keyof T> = {
key: K;
label: React.ReactNode;
render?: React.ComponentType<{item: T, value: T[K]}>;
};
type MySchema<T> = {
fields: MySchemaField<T, keyof T>[]; // <-- here is the problem: I don't want to specify the parameter K here because it depends on the single field
};
And this is how I'm expecting to use the schema:
type MyModel = {
name: string;
slug: string;
location: {address: string, country: string};
};
const schema: MySchema<MyModel> = {
fields: [
{key: 'name', label: 'Name'},
{key: 'slug', label: 'Link', render: ({value}) => value &&
<a href={`/my-path/${value}`} target="_blank" rel="noreferrer">{value}</a> || null}, // value should be inferred as string
{key: 'location', label: 'Address', render: ({value}) => <>{value.country}</>, // value should be {address, country}
],
};
I then have some React components accepting the values T
and the schema MySchema<T>
.
The underlying (React) code works just fine but I cannot find a way to correctly have value
as a field of the type T[key]
. Is there a way to do what I want or should I model differently the schema?