TypeScript Introduction

TypeScript · Lesson 1 of 28 8 min read Updated

JavaScript lets you write code quickly, but it also lets you make mistakes that only show up when a customer clicks a button. TypeScript adds types to JavaScript, so many of those mistakes are caught while you are still typing, long before the code reaches a user.

In this lesson you will learn what TypeScript is, how it relates to JavaScript, what the TypeScript compiler does, and you will run your first typed program. You should know basic JavaScript (variables, functions and objects) before you start. If you need a refresher, read the JavaScript tutorial first.

What is TypeScript?

TypeScript is JavaScript with a type system on top. A type describes what kind of value something is: a number, a string, an object with a name and a price, a list of tickets, and so on. You write these descriptions in your code, and a tool called the TypeScript compiler (tsc) checks that your code uses every value correctly.

Three facts explain almost everything about TypeScript:

  1. Every JavaScript program is already a TypeScript program. TypeScript is a superset of JavaScript: it keeps all of JavaScript and adds type syntax.
  2. Types are only for checking. When the code runs, the types are removed and plain JavaScript is left. Types never slow your program down.
  3. TypeScript runs wherever JavaScript runs: browsers, Node.js, mobile apps and servers, because what finally runs is JavaScript.

TypeScript was created at Microsoft and first released in 2012. It is open source and is now used by most large JavaScript projects, including Angular, VS Code and many React and Node.js apps.

The problem TypeScript solves

Here is a small JavaScript function for a shop in Jaipur. It looks correct, and it works when you pass numbers.

JavaScript
function billAmount(price, quantity) {
  return price * quantity + 40; // ₹40 delivery charge
}

console.log(billAmount(250, 2));
console.log(billAmount("250", 2));
console.log(billAmount(250));
Output
540
540
NaN

The second call passes the price as text, which often happens when a value comes from a form. It still prints 540 only by luck, because * converts text to a number. The third call forgets the quantity, so quantity is undefined and the bill becomes NaN (Not a Number). JavaScript gives no warning in either case. You find out when a customer sees a strange total.

Now the same function in TypeScript. The : number after each parameter is a type annotation: it says which type the value must have.

TypeScript
function billAmount(price: number, quantity: number) {
  return price * quantity + 40;
}

billAmount(250, 2);
billAmount("250", 2);
billAmount(250);
Output
app.ts(6,12): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
app.ts(7,1): error TS2554: Expected 2 arguments, but got 1.

The compiler reports both mistakes with the file name, the line and column, an error code such as TS2345, and a clear message. Your editor shows the same errors as red underlines while you type, so you fix them in seconds instead of hunting for them later.

How TypeScript works

Writing TypeScript follows a simple cycle:

  1. You write code in files ending in .ts (or .tsx for React components).
  2. The compiler checks the types and reports errors.
  3. The types are removed and JavaScript is produced, either by tsc itself or by a faster tool such as a bundler or Node.js.
  4. The JavaScript runs as usual.
StepToolOutput
Type checktsc or your editorA list of errors (or none)
Remove typestsc, Vite, esbuild or Node.jsPlain JavaScript
RunBrowser or Node.jsYour program's result

Type checking and running are separate. Even when there are type errors, tsc still writes the JavaScript file by default, because the types do not change what the code does. Treat the errors as a to-do list and fix them all.

Your first TypeScript program

Run this example, then change a value and run it again.

TypeScriptRun it yourself
const studentName: string = "Priya";
const marks: number[] = [82, 91, 77];

function average(scores: number[]): number {
  const total = scores.reduce((sum, score) => sum + score, 0);
  return total / scores.length;
}

console.log(`${studentName} scored an average of ${average(marks).toFixed(1)}`);
Output
Priya scored an average of 83.3

number[] means "an array of numbers", and the : number after the brackets of average says the function returns a number. If you tried to put the text "absent" into marks, the compiler would stop you.

Types describe objects too

Most real data is made of objects. A type gives a name to the shape of an object, and the compiler then checks every object that claims to have that shape.

TypeScriptRun it yourself
type Train = {
  number: number;
  name: string;
  from: string;
  to: string;
};

const train: Train = {
  number: 12015,
  name: "Shatabdi Express",
  from: "New Delhi",
  to: "Ajmer",
};

function describe(t: Train): string {
  return `${t.number} ${t.name}: ${t.from} to ${t.to}`;
}

console.log(describe(train));
Output
12015 Shatabdi Express: New Delhi to Ajmer

In an editor such as VS Code, typing t. inside describe shows a list of exactly four properties. If you misspell one, such as t.form, you get an error immediately. This autocomplete and instant feedback is one of the biggest reasons teams choose TypeScript.

What the compiler produces

When tsc turns TypeScript into JavaScript, it simply deletes the type syntax. For the first part of the example above, the output looks like this:

JavaScript
"use strict";
const studentName = "Priya";
const marks = [82, 91, 77];
function average(scores) {
    const total = scores.reduce((sum, score) => sum + score, 0);
    return total / scores.length;
}

Apart from the "use strict"; line, which turns on JavaScript's safer strict mode, nothing new was added. This is why TypeScript is easy to adopt: you can rename a .js file to .ts and add types a little at a time.

Common mistakes

  • Expecting types to check data at run time. Types are removed before the code runs. If data comes from a form or an API, you still need to check it with real code. You will learn how in Type Guards & Assertions.
  • Ignoring errors because the code still runs. tsc writes JavaScript even when there are errors. Errors usually point to a real bug, so fix them.
  • Adding types everywhere. TypeScript can often work out types on its own. You will see this "inference" in Basic Types & Inference.

Key points

  • TypeScript is JavaScript plus a type system; every JavaScript program is valid TypeScript.
  • Types describe values, and the compiler tsc checks that you use values correctly.
  • Types are removed before running, so they cost nothing at run time and cannot check outside data by themselves.
  • Errors appear with a file, line, column and code such as TS2345, and editors show them as you type.
  • TypeScript 7.0 has a much faster native compiler, but the language is the same.

Exercise

Write a TypeScript function ticketFare(distanceKm: number, ratePerKm: number): number that returns the fare. Call it for a 300 km trip at ₹1.5 per km and log the result. Then add a line that calls it with the distance written as text, such as "300", and think about which error tsc would report and why.

Show solution
TypeScript
function ticketFare(distanceKm: number, ratePerKm: number): number {
  return distanceKm * ratePerKm;
}

console.log(ticketFare(300, 1.5)); // 450

// ticketFare("300", 1.5);
// error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

The parameter distanceKm must be a number, so passing a string is caught by the compiler before the code ever runs.

Quick Quiz

1. What happens to TypeScript types when your program runs?

2. Which statement about TypeScript and JavaScript is true?

3. What does tsc report for billAmount(250) when the function needs two numbers?

4. What changed in TypeScript 7.0?

Learn TypeScript with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call