Expert · TypeScript basics · topic 51 of 64 · 30 min
Why TypeScript
Explanation
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.
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".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.
| Tool | What 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 bundlers | Strip the types quickly; they do not check them |
| Recent Node.js versions | Can run a .ts file directly by stripping the types; no checking |
| TypeScript Playground | A web page where you type TS and see errors and the JS output |
Setting up
# 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-tsBasic types
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 typesType 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.
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");any versus unknown
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
}Watch the lesson
Why TypeScript · 1/7
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)
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.)
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.
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
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