Adding types to a React component in TypeScript
In the types for [[React]],
@types/react
, there's an included helper for typing components called React.FC
(or the longer version React.FunctionComponent
). However, there are some downsides to using this.The component will accept
children
even if we're not using it. This happens because React.FC
implicitly sets the children
and some other values.We can't use generics
We can't use function declarations
import React from 'react'
interface AppProps {
text: string
}
// Using React.FC
const App: React.FC<AppProps> = ({ text }) => {
return <div>{text}</div>
}
// This would compile
<App text="Testing">I'm content that's not used</App>
Since React is nothing special you can use the regular syntax for defining variables to a function. This solves all of over pain points listed above.
// Same import and interface
// Using regular function typings
const App = ({ text }: AppProps) => {
return <div>{text}</div>
}
// This would NOT compile
<App text="Testing">I'm content that's not used</App>
// This would compile
<App text="Testing" />
There are multiple types we could use for the component's return type:
React.ReactElement
, JSX.Element
, React.ReactNode
. To not be too wide or too narrow with the typings, it's better to just rely on [[TypeScript]]'s inference by not adding an explicit type.