In the following TypeScript Playground example I tried to generalise the function component Element into a GenericElement component but TypeScript complains about the syntax.
How to correctly type a generic react function component in TypeScript using the React.FC type definition approach?
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.
React.FCin this case. typescriptlang.org/play?#code/…extends { toString(): string }- it is generic type parameter constraint, so provided type must havetoStringmethod (you're doingid.toString()within the function). Regarding arrow function: if you useReact.FCyou can't leave generic type parameter "open" (provided by consumer)id: string | numberfor example?