Getting Started With TypeScript
Overview
TypeScript = JavaScript + a Type System
TypeScript is an open-source language which builds on JavaScript by adding static type definitions. Types provide a way to describe the shape of an object, providing better documentation, and allow TypeScript to Validate that your code is working correctly. Writing types can be optional in TypeScript, because type inference allows you to get a lot of power without writing additional code.
The goal of theTS Type system is to help us catch errors during development. It uses ‘type annotations’ to analyze our code. The type system is only active during development. The TypeScript complier does not provide any performance optimization.
Common scenario how we would type code and run in a browser:
Environment Set Up
node and npm must be installed prior to compiler.
you will need to install the typescript complier
npm install -g typescript ts-node
If your on MacOs and get a ‘EACCESS’ error, add ‘sudo’ to the front
to test if your install was successful you can run
tsc --help
This should display a bunch of help messages on the screen if you see an error that means your npm install probably has an issue and you will need to troubleshoot.
Simple Application — TypeScript in action
Make a simple application that will make a network request to fetch some JSON and print the result.
application build flow:
- Take a look at the API we’ll use to fetch data
- Create a new project directory
- Create a package.json file
- Install axios to make a request
- Write code!
Free Fake JSON API for testing and prototyping {JSON}Placeholder. Under resources you can choose the api data you would like to work with. In this case I chose /todos, more specifically /todos/1.
Create a new project director generate a new package.json file
npm init -y
Install axios
npm install axios
Create a new file index.ts (here is where you will write your code to implement our program.) The goal of this application is to show why TypeScript is handy.
index.tsimport axios from 'axios'const url = 'http://jsonplaceholder.typicode.com/todos/1'//use axios to make a network request to the urlaxios.get(url).then(response => {
console.log(response.data)})
To run this code we must first compile this file into plain JavaScript and then we can execute the resulting JavaScript code. To do this we will do the following in the terminal.
tsc index.ts
This created a new file called index.js (the compiled version)
node index.js
You will see the Todo printed on the screen. But we can combine these commands into one!
ts-node index.ts
To print the console.log in a cleaner format pull off the id, title and completed data. Some some syntax errors are added in as well to show how TypeScript works.
index.tsimport axios from 'axios'const url = 'http://jsonplaceholder.typicode.com/todos/1'axios.get (url).then(response => {const todo =response.dataconst ID = todo.ID
cosnt title = todo.Title
const finished = todo.finishedconsole.log (`
The Todo with ID: ${ID}
Has a title of: ${title}
Is it finished? ${finished}
`)
})
If you run the file again you will see that everything returns undefined. This is an example of what TypeScript is made to prevent. TypeScript will help catch errors while in code editor as opposed to when you run your code.
index.tsimport axios from 'axios'const url = 'http://jsonplaceholder.typicode.com/todos/1'//ADDING IN TYPESCRIPT
interface Todo {
id: number;
title: string;
completed: boolean;}axios.get (url).then(response => {//Telling TypeScript that response.data is one of those Todo'sconst todo =response.data as Todoconst ID = todo.ID
const title = todo.Title
const finished = todo.finishedconsole.log (`
The Todo with ID: ${ID}
Has a title of: ${title}
Is it finished? ${finished}
`)
})
Interfaces are used to describe the structure of an object. After you add as Todo to your response.data you will immediately see 3 errors highlighted in your code. TypeScript analyzed our code using the type annotations that we added in and found the possible errors. If you hover over the errors it will provide a message telling you what is wrong. Once these errors are corrected you can run the code again in the terminal and see that the correct information is displayed.
And that is a simple introduction into TypeScript.