logo

TypeScript

- July 24, 2020

Photo by Michael Benz on Unsplash

Typescript improves Javascript in specific areas. Team collaboration is easier, the code is more robust, and the IDE can catch errors before run-time. This improves code-review and developer productivity. Typescript gets converted to Javascript at build time, as the browser can only deal with Javascript.

Progressive adoption

You can adopt typescript progressively. Your existing Javascript codebase works in Typescript because any Javascript code is valid Typescript. Typescript is just an extension of JS, not a different language.

Robust code, better collaboration

TypeScript helps to make more robust code, as some errors are checked at compile time. Giving a type to each piece of data is a way to structure your data.

The type system is a way to specify what kind of data we want to work with. By being more explicit, we remove confusion or potential misunderstandings. It makes cooperation between developers easier and more productive.

The IDE is more powerful

It makes the IDE more helpful. The IDE is able to spot inconsistencies before code execution. It can give you better autocompletion.

Get started

Use Typescript in the REPL (Shell)

npm install -g typescript npm install -g ts-node ts-node

Create a React project using Typescript

npx create-react-app project33 --template typescript

Example

You ensure a function is called with correct arguments by specifying the type of each argument.

Let's stay you created a function whose goal is to submit the card details to Stripe. Your colleague intends to use that function, but doesn't know what data to submit. In Javascript, you cannot specify types, so your function definition would be like this:

function submitCardToStripe(cardNumber,expirationDate,controlCode){ // implementation }

Unfortunately, the function caller has no idea if the cardNumber should be a number or a string. Both could make sense. With Typescript, you can indicate that each argument should be strings:

function submitCardToStripe(cardNumber:string, expirationDate:string, controlCode:string){ // implementation }

Specifying types on the function parameters allows your colleague to understand what argument he must provide. Furthermore, he will get a detailed error in case he doesn't provide the required arguments.

We may encapsulate the concept of a Card in a custom type, called an interface :

interface Card{ cardNumber:string; expirationDate:string; controlCode:string; }

The function now requires a single Card object:

function submitCardToStripe(card:Card){ const {carNumber,expirationData,controlCode} = card .. }