Skip to main content

Into to TypeScript

For this course, we will be using TypeScript instead of plain JavaScript.

TypeScript is becoming the tool of choice for JavaScript developers using modern tooling, and you are more than likely going to encounter it on your developer journey. So if you've never used TypeScript before, there's no time like the present to get stuck in!

note

Because of the way the React Native project is set up, if you are not interested in learning TypeScript, you can simply choose not to use it. Your React Native project will still run and build if you use plain JavaScript or if your types aren't correct.

You can use the TypeScript Playground to explore and try out TypeScript and the examples below.

What is TypeScript#

TypeScript is essentially "typed JavaScript". It is a superset of JavaScript, which means that all valid JavaScript code is also valid TypeScript code. TypeScript files in React Native have .ts and .tsx file extensions (instead of .js and .jsx).

TypeScript has two main usages:

1. Static Code Analysis#

It analyses your existing code and points out any incorrect usages when possible.

For example, consider the following code:

const myNum = 5;myNum.split('');

If you try this in a TypeScript file in your code editor, you should get a red underline under split with the following message:

Property 'split' does not exist on type '5'.ts(2339)

TypeScript has noticed that myNum is a number, but the split method can only be called on string types which will most certainly cause an error if we try to run this code.

2. Expand JavaScript with Custom Types#

You can also declare types for your code to communicate intent and stay type safe. For example, consider this functions that is designed for adding two numbers together:

add.js
const add = (a, b) => a + b;

Since JavaScript is not type safe, there is really nothing preventing (or even warning you) from passing in strings, objects or even functions, which could cause unintended side-effects.

With TypeScript, we can communicate the intent of these functions by declaring types for the arguments and the return type:

add.ts
const add = (a: number, b: number): number => a + b;

Now if you tried to call the add function with add("hello", "world"), you would get a warning in your code editor.

Checking for type errors#

TypeScript is the most useful during development if you use an IDE that supports just-in-time type-checking.

I would recommend use Visual Studio Code which comes with TypeScript support out of the box. VSCode and TypeScript are both built by Microsoft so they generally work very well together.

If you don't want to use VSCode, I'd recommend installing a TypeScript plugin to your favourite code editor.

tip

To check for TypeScript errors on the terminal, you can run, add

"scripts": {  "ts:check": "tsc"},

to your package.json and run

yarn ts:check# ornpm run ts:check

This is handy for checking for TypeScript errors on CI!