TypeScript continues to be one of the most loved languages as seen in the 2021 Stack Overflow developer survey. At the top 3 spots of the most loved language for 2021, it's definitely something worth exploring.
How to create React project in Typescript
You can create a new TypeScript React project by using create-react-app library in your environment and use this command:
npx create-react-app my-app --template typescript
yarn create react-app my-app --template typescript
npm install — save typescript @types/node @types/react @types/react-dom @types/jest
yarn add typescript @types/node @types/react @types/react-dom @types/jest
After running the command, you can rename all your .js files to .tsx and restart the server and get going.
The power of TypeScript comes in when you put strict: true in your tsconfig.json file. It will automatically strong typed all your variables, props and etc. Imagine you have a user object with a name and email address.
And you are passing this information down to your child component to render this information.
Strict type check on Typescript
IntelliSense helper in IDE
Same situation as the example above, when you pass down a user object from parent to child component.
IntelliSense on Typescript
So I guess you might have questions about how do you strict type your object or variables such that the code can activate Bug Catcher and IntelliSense in your React TypeScript project. 3 things to take note of to get the TypeScript Type System working for you in your React TypeScript project.
1. Declare type for primitive types variable and declare the interface for objects/array.
Type declaration for primitive types
Define interface for object to strict type the data
If you want to have an optional field in the object, you can put ? to make that field optional so that TypeScript won't bug you when checking through your code.
TypeScript showing error for missing required field as declared in your interface
Change name field to optional, no more complaint from TypeScript
2. Declare functional component type whenever necessary
Child component unable to identify user being passed down from parent
Add type declaration in your React.FC to let your component know what to expect
3. This is free for you. If you initialise a variable with a value, TypeScript will automatically infer the type for you.
Initialise your variable and TypeScript will strict type it for you for free