我正在构建基于Hooks的React App,也利用了TypeScript。
我编写了一个呈现列表的组件,并且在其中props
,它期望props.items
类型是泛型的T
:
export interface ISelectableListProps<T extends { isDisableInList?: boolean }> {
/** Specifies the item of the list. */
items: T[];
/** Unique REACT key used to re-initialize the component. */
key?: React.ReactText;
/** Specifies the template of each item. */
itemTemplate: (item: T) => JSX.Element;
}
请注意,在界面中T
还扩展了{ isDisableInList?: boolean }
,这是因为每个项目都可能具有该属性,用于禁用列表中的项目。
现在,关于SelectableList组件,我想写一下:
const SelectableListComponent: React.FC<ISelectableListProps<T>> = <T extends {}>(props) => { ... }
但是TypeScript给我一个错误,一个问题:
T
,在ISelectableListProps<T>
没有找到;props
不再推断类型:它具有any
。相反,通过删除<T extends {}>
,props
推断类型为React.PropsWithChildren<ISelectableListProps<any>>
;我发现的唯一解决方法是定义一个ItemType
,如下所示:
type ItemType = { isDisableInList?: boolean } & { [key: string]: any };
然后像这样编写组件:
const SelectableListComponent: React.FC<ISelectableListProps<ItemType>> = props => { ... }
但是,在使用组件时,这样做props.items
应该是ItemType[]
,而不是通用类型。实际上,我想这样调用组件:
<SelectableList<MyType> items={...} itemTemplate={...} />
顺便说一句,没有错误,因为ItemType
has给出了,& { [key: string]: any }
但是在我看来,这似乎是“ hacky”,几乎像using一样any
。
有什么办法可以实现我想要的?
无法使用React.FC
定义通用组件的方法。您可以只使用简单的函数定义或箭头函数,但是让TS推断类型:
export interface ISelectableListProps<T extends { isDisableInList?: boolean }> {
/** Specifies the item of the list. */
items: T[];
/** Unique REACT key used to re-initialize the component. */
key?: React.ReactText;
/** Specifies the template of each item. */
itemTemplate: (item: T) => JSX.Element;
}
const SelectableListComponent = <T extends {}>(props: ISelectableListProps<T>) => <></>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句