I'm new to React and typescript.
I've found I need to declare props as such:
const Title = ({title}:{[key:string]:any}) => {
But this seems a bit convoluted to me. Is there a better way to go about this?
I would suggest using the FC generic (which is an alias for the FunctionComponent generic). I prefer to use this as apposed to not using the generic because it appends the children property as well as types the return value from the functional component, React.Element vs JSX.Element.
import * as React from "react";
import {FC} from "react";
interface ITitleProps {
title: string;
}
// This works as expected
export const Title1: FC<ITitleProps> = ({
title,
children // Added by 'FC'
}) => {
return (
<div>
<h1>{title}</h1>
<p>{children}</p>
</div>
);
};
// This produces an error
export const Title2 = ({
title,
children // property 'children' does not exist on type 'ITitleProps'
}: ITitleProps) => {
return (
<div>
<h1>{title}</h1>
<p>{children}</p>
</div>
);
};
This GitHub was invaluable trying to figure out how to use TS with React: React TypeScript Cheatsheet