This video is available to students only

3 Ways to Add Typescript to a React Library

Adding a type-system to JavaScript.

TypeScript can be found at

TypeScript is a programming language created by Microsoft to add static types to JavaScript. It's a super-set of JavaScript, which means that all functionality in JavaScript is supported in TypeScript. We can mix JavaScript and TypeScript to allow for an easier migration between the two languages.

But what is static typing?

JavaScript is a dynamic language which means when we assign a variable let myVariable = 5; it has the type number, or int. Later in our code, it would be perfectly acceptable to assign myVariable = ["25"];. Being a dynamic language means we don't need to worry about what type of variable it is. This is in contrast to languages like C# or Go which are static languages. When a variable gets assigned a type in C#, it cannot be changed to another type. Dynamic languages are beneficial because they allow us to quickly write code; we don't need to worry about types. But, our code quickly becomes harder to maintain as teams and code get larger. Static typing let's our computer keep track of variable types so we can be productive and reduce errors.

Adding TypeScript to Scroller#

TypeScript has two ways of providing types. First, we can continue to write our code in JavaScript and include an index.d.ts file that describes the type information of our JavaScript code. Or, we can rewrite our library using TypeScript. TypeScript is flexible, so it's not one or the other — both approaches could be used together. We'll take a look at both approaches for Scroller.

Installing TypeScript#

Start by installing TypeScript as a devDependency by running yarn add typescript --dev. TypeScript will add its own CLI tool called tsc in node_modules/.bin/ which we can run using yarn tsc. To initialize TypeScript in our project run yarn tsc --init. This will create a tsconfig.json file that contains settings for TypeScript. Open tsconfig.json to find a few default settings. We'll be adding three properties to build Scroller.