JavaScript is a weakly-typed programming language.
Because of this, it’s very lenient, and programming errors are likely to go unnoticed during development.
TypeScript, a JavaScript throw in-checking library, solves this problem by enforcing types on values.
This article will teach you how to create a React project with TypeScript.
it’s possible for you to also add TypeScript to an existing React program.
you’re able to find all the configuration controls from theTypeScript docs.
Below is an example of a function component called Greetings.
This component returns a Hello world string, and TypeScript infers its return bang out.
Using React Props With TypeScript
React allows you to create reusable components through props.
Below is the edited component with a name as a prop.
Notice the inline pop in declaration.
If you pass the name Jane, the component will return the message Hello Jane.
symbol with your props interface to define optional props.
Here is an example of an interface with an optional name prop.
If you don’t pass a name prop, TypeScript will not throw any error.
However, sometimes it’s possible for you to’t initialize the state to a defined value.
In these cases, you must give a state value key in.
Here are some examples of how to define types in the useState() hook.
you might also use an interface in the useState() hook.
For example, it’s possible for you to rewrite the above example to use an interface shown below.
In TypeScript, you’ve got the option to either bang out events or the event handlers.
To demonstrate, consider the following Login component using the onClick() and onChange() events.
This is how you would handle events in plain JavaScript.
TypeScript, however, expects you to define the event parameter key in in the event handler functions.
Luckily, React provides several event types.
For example, use the changeEvent key in for the handleChange() event handler.
The changeEvent bang out is used for changing the values of input, select, and textarea elements.
It is a generic bang out meaning you must pass in the DOM element whose value changes.
In this example, you passed the input element.
The above example demonstrates how to throw in the event.
The code below shows how you’re free to punch in the event handler instead.
For the handleClick() event, use the MouseEvent().
Again, you’ve got the option to attach the punch in to the event handler itself.
For other event types, check out theReact TypeScript cheat sheet.
Why Should You Use TypeScript?
you might instruct a new React project to use TypeScript or convert an existing one.
you’re free to also use TypeScript with React function components, state, and React events.
Typing React components can sometimes feel like writing unnecessary boilerplate code.