DEV Community

Cover image for Typescript with React

Posted on

Typescript with React

I didn't think typescript with JavaScript was too bad. But when I tried it with React, I had a really hard time getting used to it. From passing down props, to setting up state, and then returning HTML, I really struggled.

Whenever passing props into a component, the type of props has to be identified. This is more lines of code to write, but it is worth it, so you don't have to try to remember which properties were in the props. Or having to flip back and forth between the file passing the props and the file receiving them. The props can be identified by types or interfaces.

type BlogProps = {
name: string;

export const Blog = ({name}: BlogProps): JSX.Element => <div>{name}</div>
Enter fullscreen mode Exit fullscreen mode

Before typescript, setting up state was simply done inside the parenthesis of setState. And when doing so with primitive types, it's still the same, just through a string or number inside the parenthesis. But when setting up state with complex types, then the type has to be identified also. This can be done by writing the type before setting state, then passing that type between setState and the ().

export const Blog = (): JSX.Element => {
const [name, setName] = useState('');
useEffect(() => setName('fede'), [])
return (<div>{name}</div>)
Enter fullscreen mode Exit fullscreen mode

Typescript errors can seem to be a paragraph long. It's also a lot of new syntaxes to get used to. When installing @types/react we get the whole react types library. This means all the HTML elements. This is what's used to check if the element is being used right. And by used right, I mean using the attributes the element has right. This also means not trying to use attributes that don't exist in the element. Then there are the custom elements. The errors from these are usually from defining the right type for the props going in them.

Typescript seems to be the solution to having to guess what type of value passes through a component. This means no more having to flip through files to see what kind of prop I'm getting anymore. It came at a cost of losing my mind learning it, but it was worth it.



Top comments (0)