Role of Typescript in React
For React development, we can develop using various languages.
- We can use JavaScript,
- We can use ECMAScript which is a standardized version of JavaScript (ES6, ES9)
- We can use TypeScript, which adds optional types to JavaScript. TypeScript is becoming extremely popular for React Applications.
- TypeScript is a superset of JavaScript and ECMAScript.
Why is the benifit of using Typescript in React
- Typescript is a strongly typed language with compile time checking and IDE support.
- Overall typescript increases developer productivity and efficiency,
- There's many online Resources on TypeScript with coding examples.
How do we convert a JavaScript application to a TypeScript application?
- Download and install TypeScript on your local system
- npm install -g typescript - install globally
- npm install -g typescript @types/node @types/react @types/react-dom @types/jest
- use --save instead of -g (for Project-Specific Installation i.e. implicitly)
- install types in your project
- npm install --save-dev @types/react @types/react-dom
- npm install --save-dev typescript @types/react @types/react-dom
- restrart your IDE
- Conver your js file to Typescript file
- Rename extension from js to tsx
- Createa tsconfig.JSON file
- npx tsc --init
- This specifies the root of the project
- specifies specifies the compiler options that are required to properly build a TypeScript project.
- Modify tsconfig.JSON file for Typescript
- Restart your IDE
- Add Types to each params and varaiable
- TypeScript needs to validate each parameter and variable within our app,
- The TypeScript syntax const user ( _userId: number, _userName: string, ) s not valid for defining a constant in a TSX file
- either user Interface or Type and then use const of either Interface type or type Type
- Remove few js files not required in js
- App.testjs
- reportWebVitals.js
- setupTests.js
- Rename fiew js file to tsx fles
- App.js to App.tsx
- index.js to index.tsx
- Remove reportWebVitals reference and imports
Uninstall Typescript
- via CLI
- npm uninstall -g typescript