我正在创建一个简单的类似模式的类型,以便使用React动态生成表.
这些是我写的类型:
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
};
这就是我希望使用模式的方式:
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}
],
};
然后我有一些接受值T
和模式MySchema<T>
的React组件.
底层(React)代码工作得很好,但我找不到一种方法来正确地将value
作为T[key]
类型的字段.有没有一种方法可以实现我想要的,或者我应该对模式进行不同的建模?