Using TypeScript
Installing TypeScript in a React project
Since TypeScript is only needed during development, we're going to --save-dev
TypeScript under development dependencies. This helps us omit TypeScript as a package when we deploy our application.
Install the TypeScript package and some specific TypeScript rules for Node.js, React, the react-dom
package and Jest:
npm install --save-dev typescript @types/node @types/react @types/react-dom @types/styled-components @types/jest
The next time you build your app or start the development server, Next.js will take care of creating the TypeScript configuration. Do so and you'll see it has created a file called next-env.d.ts
. This file is used to expose all of the framework's types so you can leverage this.
It'll also have created the tsconfig.json
file; the configuration file that's being used by the TypeScript compiler. By default, Next.js turns of TypeScript's strict mode. But in order to maximize the programming language's power, we'll enable it directly. In order to do so, set the strict
property to true
under compilerOptions
like this:
{
// [...]
"compilerOptions": {
"strict": true
// [...]
}
}
Now you're all set to start converting your JavaScript files to TypeScript!
TypeScript formatter
You can install this VSC extension to make TypeScript errors easier on the eyes.
Using TypeScript
As you have seen in the example before you can declare types by adding a colon ':' and then the type.
You can use it to be explicit about your function parameters:
function add(n1: number, n2: number) {
return n1 + n2;
}
// Or the same function in arrow notation:
const add = (n1: number, n2: number) => {
return n1 + n2;
};
Or explicit about what the function returns:
function countTeamMembers(): number {
return teamMembers.length;
}
// Or the same function in arrow notation:
const countTeamMembers = (): number => {
return teamMembers.length;
};
Or explicit about variables:
let answer: number;
let name: string;
let isAmazing: boolean;
answer = 46;
name = "Jane";
isAmazing = "Yes it is"; // TYPESCRIPT ERROR - Type 'string' is not assignable to type 'boolean'
Type inference
You should not type everything because TypeScript adds certain types automatically. You can check if it already added a type in Visual Studio Code by hovering over the variable or function. If you get a pop-up with a type you don't need to specify it. If you get a pop-up that says that the variable is of type 'any' you should specify a type.
let isAmazing = true;
/* TypeScript knows that this is a boolean because you already set it to true */
function add(n1: number, n2: number) {
return n1 + n2;
}
/* TypeScript knows that this function returns a number */