【发布时间】:2022-01-17 16:40:27
【问题描述】:
在我的 react 应用程序中,我想将特定接口作为泛型传递给非特定组件。
例如我有三个特定的接口
SpecificInterfaces.jsx
export interface InterfaceA {
name: string
age: number
...
}
export interface InterfaceB {
name: string
movies: string[]
count: number
...
}
export interface InterfaceC {
name: string
somestuff: someType
}
对于每个接口,我都有一个特定的组件 ComponentA、ComponentB 和 ComponentC。 这些组件需要在共享组件ComponentShared中使用。
现在,例如,我希望在我的 ComponentA 中返回 SharedComponent,其具有 InterfaceA 的通用类型和 InterfaceA 类型的道具,如下所示:
ComponentA.jsx
export interface Props<T> {
importData: T[]
... some props...
}
const props: Props<InterfaceA> = {
importData: importData //This is from Interface Type InterfaceA
... someProps ...
}
return (
<React.Fragment>
<SharedComponent<InterfaceA> {...props} />
</React.Fragment>
)
在我的 sharedComponent 中,我想像这样访问特定传递的泛型类型:
SharedComponent.jsx
const SharedComponent= <T,>({
importData,
...the passed Props
}: Props<T>): JSX.Element => {
importData.map((data: T) =>
data.name)
在importData.map((data:T) => data.name) 它会抛出一个错误,说 T 没有 name 的成员。所以我想我在这里传入的泛型不能正常工作,因为作为泛型传入的 InterfaceA 具有成员“名称”,就像任何其他 InterfaceB 和 InterfaceC 一样。我做错了什么?
【问题讨论】:
标签: javascript reactjs typescript generics jsx