简体   繁体   English

typescript 可以从 React 中的联合中分配基于索引的泛型类型吗?

[英]Can typescript assign index-based generic types from a union in React?

I have a React component that applies generic typings to props.我有一个将通用类型应用于道具的 React 组件。 Below is a simplified example:下面是一个简化的例子:

interface Props<T> {
  data: T
}
const MyComponent = <T,>({ data }: Props<T>) => <div /> // output not important

Let's say I want to create a component, MyGenericList that iterates over an array of values (each index-based value could be different type) and renders MyComponent .假设我想创建一个组件MyGenericList ,它迭代一个值数组(每个基于索引的值可能是不同的类型)并呈现MyComponent

How can I type MyGenericList such that each iteration of MyComponent is typed based on the type of the index-based value?如何键入MyGenericList以便MyComponent的每次迭代都根据基于索引的值的类型进行键入? Here's what I've done so far, which doesn't work:这是我到目前为止所做的,但不起作用:

interface Props<T> {
  data: (keyof T[])[];
}
const MyGenericList = <T,>({data}: Props<T>) => {
  return (
    <>{data.map(d => <MyComponent<how to get index-based generic typing of 'd' here?> data={d} /></>
  );
}

The ideal consumption of MyGenericList would be like so: MyGenericList的理想消费是这样的:

<MyGenericList<string | number | string[]>  data={['someString', 45, ['string', 'string2']} />

I was able to get this working by doing:我能够通过这样做来完成这项工作:

interface Props<T> { data: T[][] };
const MyGenericList = <T,>({ data }: Props<T>) => (
  <>{data.map(d => <MyComponent<typeof d[0]> /> )}</>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM