Reputation: 6991
I am trying to learn how to use Typescript with react and I understand that I can create the following using typescript:
import { FC } from 'react'
interface ChildProps {
color: string
}
const Child: FC<ChildProps> = ({color}) => {
return <div>{color}</div>
}
What I want to know is how can I do this with a "traditional" function. I.e., something like this:
function Child: FC<ChildProps>({color}) {
return <div>{color}</div>
}
Now, this does NOT work. I get errors. For example here is one error that I get:
What I am wondering is how is it possible to reproduce this using a traditional js function? If so, how?
Any ideas?
Thanks.
Upvotes: 1
Views: 2393
Reputation: 1028
You already know what type the parameters to FC<ChildProps>
are (i.e. ChildProps
), so you can use that. Although the comtranspiler will infer the return type when it is not defined, you can use the ReturnType
utility type to be explicit:
function Child({color}: ChildProps): ReturnType<FC<ChildProps>> {
return <div>{color}</div>;
}
Upvotes: 0
Reputation: 3965
React.FC
types a function. That’s in its name, function component
. Function types are really hard to apply to regularly named functions.
If we don’t type functions, but rather its properties, we can use any form of functions to achieve our goal.
interface ChildProps {
color: string;
}
function Child({ color }: ChildProps) {
return <div>{color}</div>;
}
Otherwise go with
import { FC } from 'react'
interface ChildProps {
color: string
}
const Child: FC<ChildProps> = ({color}) => {
return <div>{color}</div>
}
Read more about this subject here.
Upvotes: 2