在下面的TypeScript Playground示例中,我试图将函数组件Element
概括为GenericElement
组件,但TypeScript抱怨语法不正确。
如何使用React.FC
类型定义方法在TypeScript中正确键入泛型react函数组件?
import React from 'react';
type PropsType = {
id: string,
value: string,
};
type GenericPropsType<keyType> = {
id: keyType,
value: string,
};
const Element: React.FC<PropsType> = ({ id, value }) => {
return <div>{id.toString()}={value}</div>;
};
const GenericElement: React.FC<GenericPropsType<keyType>> = <keyType = string>({ id, value }) => {
return <div>{id.toString()}={value}</div>;
};
Type 'Element' is not assignable to type 'FC<GenericPropsType<any>>'.
Type 'Element' provides no match for the signature '(props: PropsWithChildren<GenericPropsType<any>>, context?: any): ReactElement<any, any> | null'.
Cannot find name 'keyType'.
Property 'keyType' does not exist on type 'JSX.IntrinsicElements'.
Cannot find name 'id'.
Left side of comma operator is unused and has no side effects.
Cannot find name 'value'.
Cannot find name 'id'.
Cannot find name 'value'.
Identifier expected.
Unexpected token. Did you mean `{'>'}` or `>`?
Expression expected.
Unexpected token. Did you mean `{'}'}` or `}`?
JSX element 'keyType' has no corresponding closing tag.
'</' expected.
'Element' is declared but its value is never read.
发布于 2021-05-07 02:43:05
基于@Aleksey L.的解释,我得到了以下可能对其他人有帮助的完整示例:
import React from 'react';
import ReactDOM from 'react-dom';
type GenericPropsType<keyType> = {
id: keyType,
value: string,
};
const GenericElement = <keyType extends string | number = string>({
id,
value = ''
}: GenericPropsType<keyType>): JSX.Element => {
return (<div>{id}={value}</div>);
};
const UseGenericElement: React.FC = () => {
return (<div><GenericElement id={4711} value="4711" /></div>);
};
ReactDOM.render(
<div><UseGenericElement /></div>,
document.getElementById('root');
);
发布于 2021-05-06 15:51:08
我认为它使用高阶函数是可行的:
import React, { FC } from 'react';
type GenericPropsType<T = any> = {
id: T,
value: string,
};
const HoC = <T,>(): FC<GenericPropsType<T>> => (props) => <div></div>
const WithString = HoC<string>() // React.FC<GenericPropsType<string>>
缺点:仅由于类型而有函数开销
我不相信我的答案是有帮助的,因为你应该显式定义泛型类型,或者你需要传递一个参数来推断它:
const HoC = <T,>(a:T): FC<GenericPropsType<T>> => (props) => <div></div>
const WithString = HoC('a') // React.FC<GenericPropsType<string>>
否则,我建议您使用@Aleksey L.
的解决方案。
https://stackoverflow.com/questions/67413371
复制相似问题