TypeScript is a strongly-typed object-oriented superset of JavaScript that compiles to plain JavaScript. What this means is that any valid JavaScript code is valid TypeScript. TypeScript is essentially JavaScript plus a type system and can be be used both as a language and a set of tools.
The type system provides type checking which can help catch errors during development. This is however optional and can be ignored in favor of JavaScript’s dynamic typing, but type checking is what makes TypeScript so powerful that it allows us to scale our applications much better.
TypeScript has a compiler that translates the instructions written in TypeScript to JavaScript. This compiler uses type annotations to analyze our code and catch errors. TypeScript’s type system is only active during development, ergo, the browser or node has no idea what TypeScript is.
It is perhaps important to note that TypeScript does not provide any performance optimization, as opposed to other strongly typed languages. You can think of TypeScript as a colleague that sits beside you while you code, helping you catch errors.
Setting up TypeScript
You need a compiler to run TypeScript as it is a compiled language, and you will need to have NodeJS installed.
In your terminal, run npm i -g typescript ts-node
to install TypeScript and ts-node (a command-line tool that allows us to compile TypeScript with one line in our terminal) globally on your computer.
If running tsc -v
and ts-node -v
both reveal the versions of TypeScript and ts-node you have installed, you’re all set!
Compiling TypeScript
You only need the compiler to run the TypeScript code. So, create a new project with npm init
. Then in the root of your project, create a file called index.ts
and put the code below in it.
To run this piece of code, we'll be using the axios npm package to fetch data from an API, so you can install that at the root of your project using npm i axios
import axios from 'axios'
const url = 'https://jsonplaceholder.typicode.com/todos/1'
const logTodo = (id, title, completed) => {
console.log(`
The Todo with ID: ${id}
Has a title of: ${title}
Is it finished? ${completed}
`)
}
axios.get(url).then((res) => {
const todo = res.data
const id = todo.ID
const title = todo.TITLE
const completed = todo.COMPLETED
logTodo(id, completed, title)
})
This code fetches some JSON data from an API and logs the result.
To compile the code, open up a terminal in your root folder and access the TypeScript compiler using the tsc command i.e tsc index.ts
.
This will generate a compiled JavaScript file called index.js. Then we can proceed to run the compiled code with node index.js
in the terminal.
Having to type tsc filename.ts
followed by ‘node filename.js’ every time we need to compile and run code can get tiring after a while so we can combine the two commands using the ‘ts-node’ module we installed earlier.
Running ts-node index.ts
in the terminal will both compile the Typescript file and run the compiled JavaScript code.
Catching errors
If you tried to run the program above, you’ll notice we have an error in the console. It logs undefined, instead of the correct values from the API.
The Todo with ID: undefined
Has a title of: undefined
Is it finished? undefined
Our program fetches data from an API and we tried to access the individual properties of the JSON objects using the wrong property labels.
Also, you may have noticed that we didn’t pass the arguments to the logTodo function in the right order. JavaScript didn’t warn us or throw an error, so we’ll use TypeScript to prevent that.
import axios from 'axios'
const url = 'https://jsonplaceholder.typicode.com/todos/1'
interface Todo {
id: number
title: string
completed: boolean
}
const logTodo = (id: number, title: string, completed: boolean) => {
console.log(`
The Todo with ID: ${id}
Has a title of: ${title}
Is it finished? ${completed}
`)
}
axios.get(url).then((res) => {
const todo = res.data as Todo
const id = todo.ID
const title = todo.TITLE
const completed = todo.COMPLETED
logTodo(id, completed, title)
})
As you can see, the changes here from the initial vanilla JavaScript code are:
First,
interface
describes the requirements (types of data) in the object ‘todo'. Interfaces are used to describe the structure of an object. It’s worth pointing out that the type checker does not require that these properties come in any sort of order, only that the properties the interface requires are present and have the required type.Also, we added a few type annotations, : string, : boolean, and : number. This allows TypeScript to warn us to fix the order of our arguments if we do them incorrectly, whereby JavaScript wouldn’t let us know until we compile our code which is a bit inefficient from a developer perspective. By adding a bit of type annotation, we can avoid this problem.
You would realize that as soon as we made those changes, our code editor starts moaning about possible errors, so we fix them by using the correct arguments and property labels, and then when we run the program again, it logs the right result to the console.
import axios from 'axios'
const url = 'https://jsonplaceholder.typicode.com/todos/1'
interface Todo {
id: number
title: string
completed: boolean
}
const logTodo = (id: number, title: string, completed: boolean) => {
console.log(`
The Todo with ID: ${id}
Has a title of: ${title}
Is it finished? ${completed}
`)
}
axios.get(url).then((res) => {
const todo = res.data as Todo
const id = todo.id
const title = todo.title
const completed = todo.completed
logTodo(id, title, completed)
})
The Todo with ID: 1
Has a title of: delectus aut atem
Is it finished? false
One of the goals of TypeScript is to help us catch extremely common errors during development, helping us become more efficient developers. Checkout the TypeScript handbook to learn more about its syntax and cool features.
Top comments (2)
Thank you for the article, it was very helpful.
Is the name master_elodin a reference from Kingkiller chronicles?
Yes, it is. 😅