【发布时间】:2021-05-10 11:01:51
【问题描述】:
我正在尝试创建一个 React 组件,它可以基于某个 prop 值具有动态 props,但我卡在了类型声明中......
const layerMap = {
l1: {
text: 'l1 text'
},
l2: {
image: 'l2 image'
}
};
type ElProps<T, K extends keyof T, NK extends keyof T[K]> = {
layerName: K;
[P in NK]: T[K][NK];
/* ^^^^^^^^^
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
*/
};
function Elem<
L extends typeof layerMap,
LKey extends keyof L,
LPKey extends keyof L[LKey]
>(props: ElProps<L, LKey, LPKey>) {
return <h1>element</h1>;
}
我的目标是让组件Elem可以这样使用,根据传递的layerName的值生成动态props
/*
when layerName is `l1`, Elem's props will be { layerName: string, text: string; }
when layerName is `l2`, Elem's props will be { layerName: string, image: string; }
*/
const App = (props: any) => (
<div>
<Elem layerName="l1" text="text" />
<Elem layerName="l2" image="image" />
</div>
)
【问题讨论】:
标签: reactjs typescript