打字稿反应,基于特定道具值的动态道具?

时间:2021-02-06 07:24:19

标签: reactjs typescript

我正在尝试创建一个 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>
)

1 个答案:

答案 0 :(得分:0)

我终于弄清楚了,通过使用交集类型(& 运算符)

ts playground demo

import React from "react";

const layerMap = {
  l1: {
    text: 'l1 text'
  },
  l2: {
    image: 'l2 image'
  }
};

type ElProps<T, K extends keyof T, NK extends keyof T[K]> = {
  [P in NK]?: T[K][NK];
} & { layerName: K };

function Elem<
  L extends typeof layerMap,
  LKey extends keyof L,
  LPKey extends keyof L[LKey]
>(props: ElProps<L, LKey, LPKey>) {
  return <h1>element {props.layerName}</h1>;
}

function App() {
  return (<>
    <Elem layerName="l1" text="x" />
    <Elem layerName="l2" image="x" />
  </>);
}

export default App;