Skip to content

Expert · TypeScript basics · topic 51 of 64 · 30 min

Why TypeScript

Explanation

TypeScript is JavaScript plus types. A type says what kind of value a variable or parameter may hold, and the editor warns you while you type when the code breaks that rule. Before the code runs, the types are removed and plain JavaScript is left, so the browser never sees them.

What is TypeScript?

TypeScript is a language made by Microsoft and released as free, open-source software. It is JavaScript with one addition: types. A type is a label that says what kind of value something holds: a number, a string, a list of products, and so on. Almost any JavaScript file is already valid TypeScript, so you can start small.

Think of it like this: Think of a railway reservation form. The age box takes only a number, and the quota box takes only GN, TQ or LD. The clerk checks the form before printing your ticket, so a mistake is fixed at the counter, not on the train. TypeScript is that clerk: it checks your code before users ever see it.
typescript
function addGst(price: number): number {
  return price + price * 0.18;
}

addGst(100);   // 118
addGst("100"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
// In plain JavaScript, addGst("100") quietly returns "10018".
The red line appears in VS Code as soon as you type the wrong call

How it runs: the types are removed

Browsers run JavaScript, not TypeScript. The TypeScript compiler, called tsc, does two jobs: it checks the types, and it writes out plain JavaScript with the types removed. Build tools like Vite only strip the types (fast, no checking), so the checking comes from your editor and from running tsc.

ToolWhat it does with types
VS Code (editor)Checks while you type and shows red underlines
tsc (the compiler)Checks the whole project; can also write .js files
Vite and other bundlersStrip the types quickly; they do not check them
Recent Node.js versionsCan run a .ts file directly by stripping the types; no checking
TypeScript PlaygroundA web page where you type TS and see errors and the JS output

Setting up

bash
# add TypeScript to an existing project (as a dev dependency)
npm install -D typescript
npx tsc --init      # creates tsconfig.json, the settings file
npx tsc --noEmit    # check every file, write nothing

# or start a new React + TypeScript app with Vite
npm create vite@latest my-app -- --template react-ts
Two common ways to start; the Playground needs no setup at all

Basic types

typescript
let name: string = "Asha";
let age: number = 21;
let isMember: boolean = true;
let marks: number[] = [80, 92, 75];
let cities: Array<string> = ["Pune", "Kochi"]; // same as string[]
let pinEntry: [string, number] = ["Bengaluru", 560001]; // a tuple: fixed length, fixed types
A colon after the name gives the type

Type inference: let the compiler guess

You do not have to write every type. When you write let count = 0, TypeScript infers (works out) that count is a number. Write types where the compiler cannot guess: function parameters, empty arrays, and values from outside your code.

typescript
let count = 0;          // inferred: number
count = "five";         // Error: Type 'string' is not assignable to type 'number'.

const names: string[] = []; // an empty array needs a type
names.push("Ravi");
Inference keeps code short and still safe

any versus unknown

typescript
const a: any = JSON.parse(text);
a.toUpperCase();   // no error now, may crash later

const u: unknown = JSON.parse(text);
u.toUpperCase();   // Error: 'u' is of type 'unknown'.
if (typeof u === "string") {
  u.toUpperCase(); // OK: we checked first
}
any switches checking off; unknown makes you check before use
Tip: Open the TypeScript Playground in a browser tab while you learn. Type a few lines, hover over a variable to see its type, and look at the JavaScript it produces on the right.
Careful: Types disappear when the code runs. TypeScript cannot check data that arrives at runtime, like an API reply or a form value. You still have to check that data yourself (you will learn how in this module).

Watch the lesson

Why TypeScript · 1/7

TypeScript = JavaScript + types

TypeScript is JavaScript plus types. A type says what kind of value something holds.

Prefer a video by a teacher? Find free videos on “typescript tutorial for beginners javascript developers” on YouTube ↗

In real life: A shop app that stops a costly bug

A developer at a small grocery start-up changes price from a number to a string in one place. In plain JavaScript, every bill would quietly join text instead of adding ("60" + 20 gives "6020") and customers would see wrong totals. With TypeScript, VS Code underlines all 14 places that use price within a second, and the bug is fixed before anyone opens the app.

Practice (0/3 done)

Task 1 · Code · Typescript

Write a typed function totalMarks(marks: number[]): number that returns the sum of all the marks. totalMarks([80, 90, 75]) returns 245 and totalMarks([]) returns 0. (The types are removed before the code runs, so the checks test what your function returns.)

Task 2 · Code · Typescript

Data from a form or an API can be anything, so take it as unknown. Write toNumber(value: unknown): number. If value is a number, return it. If it is a string and Number(value) is not NaN, return that number. For anything else (other text, true, null, an object) return 0. Examples: toNumber(7) is 7, toNumber("42") is 42, toNumber("abc") is 0, toNumber(null) is 0.

Task 3 · Practice

Set up TypeScript on your computer and watch it catch a bug. In an empty folder run npm init -y, npm install -D typescript and npx tsc --init. Create hello.ts with a function addGst(price: number): number, call it once correctly and once with "100". Look at the red line in VS Code, then run npx tsc and read the error. Finally, paste the same code into the TypeScript Playground and compare.

Quick quiz

Question 1

1.What does the TypeScript compiler (tsc) produce from your .ts files?

Question 2

2.let count = 10; What type does TypeScript infer for count?

Question 3

3.Line 1: let city = "Pune"; Line 2: city = 411001; Which line does TypeScript mark as an error?

Question 4

4.Why is unknown safer than any?

Question 5

5.Recent Node.js versions can run a .ts file directly. What do they do with the types?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: Testing basics: unit, integration and end-to-end