TypeScript basics
TypeScript is JavaScript plus types: the compiler checks your code before it runs, so bugs like a string price joining into a wrong cart total are caught at compile time instead of on the user's bill.
21.1 The problem: a wrong total with no error
- getTotal adds item.price for every cart item; the logic looks correct.
- The Shirt price came from a form, so it is the string "499", not a number.
- In JavaScript number + string does not add, it joins: 0 + "499" + 299 gives "0499299".
- No error is thrown, so the wrong total goes straight to the user's bill.
JavaScript
function getTotal(cart) { let total = 0; for (const item of cart) { total = total + item.price; } return total;} const cart = [ { name: "Shirt", price: "499" }, { name: "Socks", price: 299 },];console.log(getTotal(cart));Output
049929921.2 How TypeScript works
- JavaScript is dynamically typed: a variable's type is decided at run time, so wrong data moves ahead silently.
- TypeScript = JavaScript + types. You annotate types, and the compiler (tsc) checks everything before the code runs.
- After checking, tsc removes the types and emits plain JavaScript; the browser only ever runs JavaScript.
- Step 1
1.cart.ts: code + types
- Step 2
2.tsc check: errors reported up front
- Step 3
3.cart.js: types removed
- Step 4
4.Browser / Node runs only plain JavaScript
Types exist only at compile time; they are erased in the output
21.3 Fix: add types
- type Item says every item has name: string and price: number.
- cart: Item[] types the parameter; ): number is the return type.
- tsc reports the string price on line 12 before the code ever runs.
TypeScript
type Item = { name: string; price: number }; function getTotal(cart: Item[]): number { let total = 0; for (const item of cart) { total = total + item.price; } return total;} const cart: Item[] = [ { name: "Shirt", price: "499" },];Output
$ npx tsc cart.tscart.ts(12,20): error TS2322:Type 'string' is not assignable to type 'number'.21.4 Basic types and inference
- string, number, boolean: the everyday primitives.
- number[]: an array of numbers (type followed by []).
- [string, number]: a tuple, a fixed-length array where each position has a fixed type.
- Type inference: let city = "Pune" is inferred as string without writing a type, so city = 42 is an error.
- void: the function returns nothing.
TypeScript
let userName: string = "Rahul";let age: number = 25;let isPrime: boolean = true;let scores: number[] = [90, 85, 77];let entry: [string, number] = ["Rahul", 90]; let city = "Pune"; // inferred: stringcity = 42; function log(msg: string): void { console.log(msg);}Output
$ npx tsc basics.tsbasics.ts(8,1): error TS2322:Type 'number' is not assignable to type 'string'.21.5 any vs unknown
- any switches checking off: every property and method is allowed, so the typo data.prize compiles fine.
- The bug then appears at run time as a TypeError.
- unknown can also hold any value, but you must check it before use.
- Calling input.toFixed directly is an error; inside if (typeof input === "number") it is allowed. This check is called narrowing.
TypeScript
function parse(text: string): any { return JSON.parse(text);} const data = parse('{"price": 499}');console.log(data.prize.toFixed(2));Output
$ npx tsc any.ts$ node any.jsTypeError: Cannot read propertiesof undefined (reading 'toFixed')TypeScript
const input: unknown = JSON.parse("499"); input.toFixed(2); if (typeof input === "number") { console.log(input.toFixed(2));}Output
$ npx tsc unknown.tsunknown.ts(3,1): error TS18046:'input' is of type 'unknown'.| Point | any | unknown |
|---|---|---|
| Can hold any value | Yes | Yes |
| Type checking | Off | On, must narrow first |
| Using a property directly | Allowed (may crash at run time) | Compile error until checked |
| When to use | Avoid; legacy/migration only | Unknown input such as JSON.parse or API data |
21.6 interface vs type
- Both describe the shape of an object.
- email?: string means the property is optional.
- interface Admin extends User copies all User properties and adds permissions.
- A type alias can also describe unions (string | number), tuples and primitives; an interface cannot.
TypeScript
interface User { id: number; name: string; email?: string;} interface Admin extends User { permissions: string[];} type Id = string | number;type Point = [number, number]; const asha: User = { id: 1, name: "Asha" };| Point | interface | type |
|---|---|---|
| Object shape | Yes | Yes |
| Extend | extends keyword | Intersection (&) |
| Same name declared twice | Merges (declaration merging) | Error |
| Unions, tuples, primitives | No | Yes |
| Usual preference | Objects | Unions and everything else |
21.7 Union types
- type Id = string | number: an order id can be "A12" or 42.
- printId("A12") and printId(42) are valid; printId(true) is an error because boolean is not in the union.
- On a union you can only use what every member supports; otherwise narrow with typeof first.
TypeScript
type Id = string | number; function printId(id: Id) { console.log("Order:", id);} printId("A12");printId(42);printId(true);Output
$ npx tsc union.tsunion.ts(9,9): error TS2345:Argument of type 'boolean' is notassignable to parameter of type 'Id'.Checkpoint: will this compile? No, toUpperCase exists only on string, and id may be a number.
TypeScript
function format(id: string | number) { return id.toUpperCase();}Output
$ npx tsc checkpoint.tscheckpoint.ts(2,13): error TS2339:Property 'toUpperCase' does not existon type 'string | number'.21.8 Common mistakes
- Using plain string for a fixed set of values: a typo like "piad" is accepted. Use a literal union so it is an error and the editor autocompletes.
- Reaching for any to silence errors: use unknown and narrow.
- Believing TypeScript checks types at run time: types are removed after compiling, so wrong-shaped API data is not caught. Validate at run time with a library like Zod.
TypeScript
// Wrong: plain string, "piad" is acceptedtype Order = { id: number; status: string;}; const order: Order = { id: 1, status: "piad",};TypeScript
// Right: literal union, "piad" is an errortype Order = { id: number; status: "pending" | "paid";}; const order: Order = { id: 1, status: "piad",};21.9 Three rules from day one
- Keep "strict" on in tsconfig; that is what gives real safety.
- Avoid any; use unknown when you do not know the type.
- Write types on function parameters, trust inference for simple variables.
21.10 Interview tips
- TypeScript is JavaScript + types; errors are caught at compile time and the output is plain JavaScript.
- interface vs type: both describe objects; interface extends and merges, type also does unions, tuples and primitives and combines with &.
- Prefer interface for objects and type for unions.
- any turns checking off; unknown forces a check (narrowing) before use.
- TypeScript gives no run-time checks: use Zod (or similar) for API data.