Skip to content

Expert · TypeScript basics · topic 42 of 61 · 20 min

Why TypeScript

Explanation

TypeScript is JavaScript with types added. You describe what kind of value each variable, parameter and return value holds, and the TypeScript compiler (tsc) checks your code BEFORE it runs, catching typos and wrong values. The types are then removed, so what runs is plain JavaScript.

The problem TypeScript solves

JavaScript only finds many mistakes when the code runs, sometimes in front of a customer: calling a function with arguments in the wrong order, misspelling a property (user.nmae), or forgetting that a value can be null. In a 200,000-line codebase with 30 developers, these bugs are expensive. TypeScript (made by Microsoft, first released in 2012) adds a type system that checks the code while you write it.

typescript
function totalPrice(price: number, qty: number): number {
  return price * qty;
}
totalPrice(499, 2);       // OK
totalPrice('499', 2);     // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
const u = { name: 'Asha' };
u.nmae;                   // Error: Property 'nmae' does not exist. Did you mean 'name'?
These errors appear in your editor as red underlines, before you run anything.

How it works

  1. You write .ts files (or .tsx for React) with type annotations like : number.
  2. The TypeScript compiler, tsc, checks the types and reports errors.
  3. It outputs plain .js files with the types removed (this is called type erasure). Browsers and Node run that JavaScript.

Because types are erased, they do NOT exist at run time. TypeScript cannot check data that arrives while the program runs, such as JSON from an API. You still need run-time checks at those boundaries.

Getting started

bash
npm install --save-dev typescript
npx tsc --init          # creates tsconfig.json
npx tsc                 # type-check and compile
npx tsc --noEmit        # only type-check (common in projects that use a bundler)

tsconfig.json holds the settings. The most important one is "strict": true, which turns on the full set of checks, including strictNullChecks (null and undefined must be handled). Always start new projects with strict on; turning it on later is painful.

Type inference: you do not annotate everything

TypeScript works out (infers) types from values. let count = 0 is already a number; writing let count: number = 0 adds nothing. Annotate function parameters, and the return type of important functions; let inference handle most local variables.

typescript
let city = 'Pune';     // inferred: string
city = 42;             // Error: Type 'number' is not assignable to type 'string'.
const prices = [10, 20]; // inferred: number[]
const total = prices.reduce((a, b) => a + b, 0); // inferred: number
Careful: A common beginner habit is silencing every error with the any type. any turns off checking for that value, and the "anyness" spreads to everything it touches. Use unknown when you truly do not know a type (next topic), and fix the real problem instead.
Think of it like this: TypeScript is like the spell-checker and grammar checker in a word processor. It underlines mistakes while you type, but it is not part of the printed letter. The reader (the browser) only ever sees the final text.
Tip: You can try TypeScript without installing anything in the official Playground at typescriptlang.org/play. Many editors, including VS Code, use TypeScript to power autocomplete even in plain .js files.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Why TypeScript · 1/6

TypeScript

In this module you will learn TypeScript, which is JavaScript with types.

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

In real life: Renaming a field across a large app

A logistics company renamed the field deliveryDate to expectedDelivery in its API. In the TypeScript front end, changing the type definition immediately showed red errors in all 47 places that used the old name, so the team fixed them before release. In an older plain-JavaScript admin panel, three pages silently showed "undefined" for a week.

typescript
interface Shipment {
  id: string;
  expectedDelivery: string; // was deliveryDate
}
function label(s: Shipment) {
  return `${s.id}: ${s.expectedDelivery}`; // s.deliveryDate would now be an error
}

Practice (0/3 done)

Task 1 · Code · Typescript

Add types and fix the bug: totalPrice(price: number, qty: number): number should return price × qty, but it currently adds them.

Task 2 · Question

What does the browser actually run when you use TypeScript?

Task 3 · Code · Typescript

Types are erased at run time, so data from outside must be checked by code. Write parseQty(input: unknown): number that returns the input if it is a whole number from 1 to 99, and throws an Error "Invalid quantity" otherwise.

Quick quiz

Question 1

1.When does TypeScript report type errors?

Question 2

2.What does "type erasure" mean?

Question 3

3.Which tsconfig option should new projects turn on?

Question 4

4.let n = 5; n = "five"; In TypeScript this is…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

When does TypeScript report type errors?

Answer: Before running, when you compile or in the editor

Type checking happens at compile time.

What does "type erasure" mean?

Answer: Types are deleted from the output JavaScript

tsc removes annotations; they do not exist at run time.

Which tsconfig option should new projects turn on?

Answer: "strict": true

strict enables the full set of useful checks.

let n = 5; n = "five"; In TypeScript this is…

Answer: An error: string is not assignable to number

n was inferred as number.

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

Answer: Plain JavaScript with the types removed

tsc checks the types and writes JavaScript without them, because browsers and Node.js run JavaScript.

From Why TypeScript

In a Vite project, why does tsconfig.json often have "noEmit": true?Related

Answer: Because Vite builds the JavaScript; TypeScript is only used to check types

Vite strips types and bundles the code. tsc (or the editor) only needs to check, so it writes no files.

From TypeScript in real projects

What does a return type of void mean?Related

Answer: The function does not return a useful value

void is for functions that do a job (like logging) and do not give back a value.

From Typing functions and objects

Where should an API key live?Related

Answer: In an environment variable / .env file that is not committed

Secrets stay out of the code and out of Git.

From Real project tooling

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

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “TypeScript basics” before its exam: Basic types and inference, Object types, interfaces and unions, Generics, Utility types and real-world TypeScript.
  2. Module 9 exam: TypeScript basics · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functional patterns and testing. 61 topics left in the course before the final exam.

← Previous: fetch: talking to servers