Using typescript with react.
Meet Vaghasiya
Passionate Vue.js & Laravel Developer | JavaScript Lover | Eager to Learn
Here we will learn step by step process for starting the #typescript with a #reactjs .
Steps:
npx create-react-app your-app --template typescript
you will see, the TSX file in the src folder. it's similar to the JSX but with extra type annotation.
Delete this src folder. we will write code from scratch for better understanding.
2. now make a new index.tsx file in the src folder and write the below code in that. here you notice that we do not write any code specific to typescript but still it's valid typescript code. and if you hover on any element then it will show types. this is called type inference means typescript auto guess type value given by their initial value.
DEFINE PROPS TYPE
if we pass props, as normal, then it will show the below error. we tell typescript to the interface of particular props.
to avoid this error, make a new interface for props and assign them as shown below.
DEFINE STATE TYPE
We can define property as we define in the normal javascript class. Let's make a simple counter for our app.
领英推荐
2. But let's say we want to initialize the state in the constructor function. in javascript, their both are the same. but in typescript, it will give an error.
the state is inherited properly from React.component. and which default value is {}. so typescript didn't get count property value in state object (it's empty from typescript perspective.). to solve this pass second state interface as the second argument of generics in React.component
however if we define the state in the current App component as shown in the first example, then it will override the state variable. so in that case typescript got to state.count and not throw an error.
if we give any other property then count, typescript gives an error.
?constructor(props: AppProps) {
? ? super(props);
? ? this.state = { num: 0 }; ?// Type '{ num: number; }' is not assignable to type
'Readonly<AppState>'
? }
3. but what if use provide both methods, like property state in App component and also give AppState generics to React.component?
in this scenario, state property must have count property. apart from this, if we add new property then it will merge both types. like below we add num 0. so typescript have now both count and num value. and will not throw errors as above.
Use typescript in the functional components.
we can pass prop types as a normal function parameter types.
for defining the type of state, we can pass as generics to state function as shown below.