Introduction
Why Use TypeScript in React Project
TypeScript makes your code easier to maintain:
- it reduces bug (by catching error in build time instead of runtime).
- it is easier and safer to refactor.
- it make code self-documented.
However, TypeScript has some downsides too:
- Definitely higher learning curve than JavaScript.
- Slightly less references and helps compared to JavaScript.
- May take longer time to write, especially when you’re still new.
Why Learn TypeScript as React Developer
-
Better job prospect
-
Improves your JavaScript skill
Just like React helps you to write better JavaScript by making write pure function a second nature, TypeScript would help you to write better JavaScript by making you more thoughtful about your data structure. Many times when a code is hard to implement in TypeScript because it is dynamic, it is probable that you had over-complicated your code.
Scope of This Workshop
This workshop covers
- TypeScript fundamentals required to use it in React
- How to slowly migrate your React codebase from JavaScript to TypeScript
- Common usage pattern when using TypeScript with React
This workshop does not cover
- React fundamentals (covered in another workshop, Introduction to React v2)
- Modern JavaScript (covered in another workshop, JavaScript: The React Parts)
- All TypeScript concepts (I only focus on those most relevant to React. Many TypeScript concepts are omitted, e.g. type safe OOP,
enum
, andnamespace
). - How to configure TypeScript pipeline (I will use Create React App which already configure the pipeline).
How TypeScript reduces Bug
Let’s explore that in more details how do TypeScript reduces bug.
In its essence, TypeScript is making your code type-safe, or in a more layman term, use types to prevent code from doing invalid things.
What are the invalid things? Here are two examples:
- multiplying a number with an array.
- pass a function with string when the function actually expects an array.
Consider the following example:
const append = (array, item) => array.concat(item);
const excludeUndefined = (array) => array.filter((item) => typeof item !== 'undefined');
const newList = append([1, 2, undefined, 6], undefined);
const numbers = excludeUndefined(newList);
console.log(numbers);
/* Uncomment the code below and you will get error */
// const newList2 = append('malcolm', undefined);
// const newName = excludeUndefined(newList2);
// console.log({ newName });
const append = (array, item) => array.concat(item);
const excludeUndefined = (array) => array.filter((item) => typeof item !== 'undefined');
const newList = append([1, 2, undefined, 6], undefined);
const numbers = excludeUndefined(newList);
console.log(numbers);
/* Uncomment the code below and you will get error */
// const newList2 = append('malcolm', undefined);
// const newName = excludeUndefined(newList2);
// console.log({ newName });
When we write the function append
and excludeUndefined
, we assume the first parameter is an array. However because JavaScript is a weakly-typed language, you can pass a string to the functions, and JavaScript will still allows you to do so, which cause an error when the code runs.
Using TypeScript, we can document our code explicitly, like below. (Don’t worry about the syntax, which I will explain in details later)
const append = <T>(array: T[], item: T): T[] => array.concat(item);
const excludeUndefined = <T>(array: Array<T | undefined>): T[] =>
array.filter((item) => typeof item !== 'undefined');
const newList = append([1, 2, undefined, 6], undefined);
const numbers = excludeUndefined(newList);
console.log(numbers);
/* Uncomment the code below and you will get error from TypeScript */
// const newList2 = append('malcolm', undefined);
// const newName = excludeUndefined(newList2);
// console.log({ newName });
const append = <T>(array: T[], item: T): T[] => array.concat(item);
const excludeUndefined = <T>(array: Array<T | undefined>): T[] =>
array.filter((item) => typeof item !== 'undefined');
const newList = append([1, 2, undefined, 6], undefined);
const numbers = excludeUndefined(newList);
console.log(numbers);
/* Uncomment the code below and you will get error from TypeScript */
// const newList2 = append('malcolm', undefined);
// const newName = excludeUndefined(newList2);
// console.log({ newName });
Now that TypeScript will start yelling at us when we pass a string to the append
function as it contradicts the assumption of the append
function, so that we can identify problem in our code without running the code.
One way to think about all these is using TypeScript is nothing but making your code assumption explicit so that TypeScript can cross-check assumptions throughout your code.
- When you state your assumptions of variable/parameter, you are annotate the variable with type.
- The process of TypeScript validates all your types does not contradicts each other (e.g. assume function accept array but pass it string) is known as type-checking.
Overview of Code-Along Project
In this workshop we will migrate an existing React project to use TypeScript.
The site is called Shopit, an E-commerce SPA.
- Live version
- Code repository
- Branch that we will start with
- Branch we will aims to target (use this as reference when you’re stuck)
Project Setup
Let’s setup the project locally before we go further:
-
Clone the project and checkout
redux
branch:git clone -b redux https://github.com/malcolm-kee/react-ecomm-site.git
-
Install the dependencies:
cd react-ecomm-site yarn install
If you have not installed
yarn
, replace theyarn
command withnpm install
.
Libraries used in the project:
- Create React App for build pipleline.
@reach/router
for client-side routing.redux
for state management.react-styleguidist
for component development environment.
Don’t worry if you’re not familar with those libraries as I will explain them whenever required. But don’t get excited that you will master all of them after this workshop, I will not go deep into them.
The focus of this workshop is using TypeScript in React. The reason I include those libraries into the project is to make it more like a real-life project so that it is easier for you to translate what you learn today and apply them to your work.
Setup
To avoid the workshop time being spent on downloading and installing tools, make sure you have the following software installed before the workshop starts:
- node.js and npm (Download)
- git (Download)
- VS Code (Download) - you can use other editor if you wish, but VS Code has best default TypeScript integration as far as I know, as VS Code team work closely with TypeScript team within Microsoft.
Besides, sign up a GitHub account if you doesn’t have one yet.
Looking Ahead
The lessons of the workshops will be vaguely consists of the following sections:
-
Intro and prerequisite: we will discuss what is TypeScript and its relationship with JavaScript. We will also briefly go through React Styleguidist, a library that help you to develop React components in isolation as this is where we will write our code today.
-
TypeScript fundamentals: we will discuss the basic concepts in TypeScript, how to use it, and how it will catch type error.
-
TypeScript in React: we will get our hand dirty by installing TypeScript in our React projects, applying what we have learnt. And then we will discuss a slightly advanced topics like generics and typeguard and how to use them in React.