TypeScript Preview ADVANCED
JavaScript-এর উপর static type — ২০২০-এর industry default
1. What TS Adds
TypeScript is JS plus a static type-checker that runs at compile time. The output is plain JS — types are erased before runtime, costing zero performance. The benefit: bugs caught while you type, contracts documented in code, and refactor confidence.
2. Install & Run
$ npm install -D typescript
$ npx tsc --init # creates tsconfig.json
$ npx tsc # compile *.ts → *.js
$ npx tsc --watch # incremental rebuild
3. Basic Types
let n: number = 42;
let s: string = "hi";
let ok: boolean = true;
let nothing: null = null;
let absent: undefined = undefined;
let big: bigint = 10n;
let nums: number[] = [1, 2, 3];
let mixed: (number|string)[] = [1, "two"];
let pair: [string, number] = ["age", 22]; // tuple
let any_: any = 1; // disables checking — avoid
let some: unknown = 1; // safer "any"
function log(msg: string): void { console.log(msg); }
function fail(): never { throw new Error(); }
4. Interfaces & Type Aliases
interface User {
id: number;
name: string;
email?: string; // optional
readonly createdAt: Date;
}
type Status = "active" | "archived" | "draft"; // union literal type
type Pair<K, V> = { key: K; value: V }; // generic alias
function greet(u: User): string {
return `hi, ${u.name}`;
}
const u: User = { id: 1, name: "Arif", createdAt: new Date() };
console.log(greet(u));
5. Generics
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
const a = first([1, 2, 3]); // number | undefined
const b = first(["a", "b"]); // string | undefined
interface Box<T> {
value: T;
}
const stringBox: Box<string> = { value: "hi" };
The runnable equivalent (no types, but same logic):
const first = arr => arr[0];
console.log(first([1, 2, 3]));
console.log(first(["a", "b"]));
6. Narrowing
function describe(x: string | number) {
if (typeof x === "string") {
return x.toUpperCase(); // x is string here
}
return x.toFixed(2); // x is number here
}
function isError(x: unknown): x is Error { // user-defined guard
return x instanceof Error;
}
7. tsconfig.json Essentials
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true, // turn on every strict check
"noUnusedLocals": true,
"skipLibCheck": true,
"outDir": "dist"
},
"include": ["src"]
}
"strict": true
Without it, TS lets null/undefined pass everywhere — half the value disappears. strict turns on strictNullChecks, noImplicitAny, and friends.
8. Migration Path: JS → TS
- Add
typescriptas devDep, runtsc --init - Set
"allowJs": trueand"checkJs": falseinitially - Rename one
.jsat a time to.ts - Sprinkle
anywhere you don't have time — fix later - Turn on
"strict"when the surface is mostly typed - Stop here — most apps thrive at 80% strict, not 100%
9. Glossary (শব্দকোষ)
| Term | Meaning | বাংলায় |
|---|---|---|
| TypeScript | JS + a static type-checker. Erased at compile time. | JS + static type checker; compile-এ types erase হয়। |
tsc | The TypeScript compiler. | TypeScript compiler। |
tsconfig.json | Compiler options file for a TS project. | TS project-এর compiler config। |
| strict mode | "strict": true turns on null-checks, no-implicit-any, etc. | সব strict check on করে। |
| Type alias | type X = ... — a name for a type. | Type-এর জন্য name দেওয়া। |
| Interface | Object shape definition — extendable. | Object shape — extend করা যায়। |
| Union | A | B — value can be one of several types. | একাধিক type-এর যেকোনো একটি। |
| Generic | function f<T> — type parameter for reusable shapes. | Reusable shape-এর জন্য type parameter। |
| Narrowing | Refining a union to a single type via guards. | Guard দিয়ে union থেকে এক type-এ নামানো। |
any / unknown | Disable checks (avoid) / safe escape hatch (prefer). | any avoid; unknown safer। |
strict on; boundary-তে unknown, ভেতরে narrow করে concrete type। Migration এক ফাইল করে — allowJs দিয়ে শুরু করুন।
10. Practice Problems
- Write a TS function signature for "add(a, b)" returning a number.
✨ Show Answer
function add(a: number, b: number): number { return a + b; } - Define an interface User with required name and optional email.
✨ Show Answer
interface User { name: string; email?: string; } - Define a Status union of three string literals.
✨ Show Answer
type Status = "active" | "archived" | "draft"; - Write a generic identity function.
✨ Show Answer
function id<T>(x: T): T { return x; } - Show the JS-equivalent that would run in a browser sandbox.
✨ Show Answer
a5.jsconst id = x => x; console.log(id(42), id("hi")); - Why is
unknownsafer thanany?✨ Show Answer
Answer:
anyopts out of all type checking — TS won't complain even if you call methods that don't exist.unknownsays "I don't know yet" but forces you to narrow (typeof, instanceof, custom guard) before you use it.unknownat the boundary, types inside. - Write a type-narrowing function that returns the length whether arg is string or array.
✨ Show Answer
function len(x: string | unknown[]): number { return x.length; } - Why turn on
"strict": true?✨ Show Answer
Answer: Without it, you keep most of JavaScript's flexibility — and most of its bugs.
strictturns on null checks, no-implicit-any, strict function signatures, etc. — the rules that catch real bugs in production. Adoption is the difference between TypeScript-the-buzzword and TypeScript-the-tool. - Show a
readonlyfield that prevents reassignment.✨ Show Answer
interface User { readonly id: number; name: string; } const u: User = { id: 1, name: "Arif" }; // u.id = 2; // Error: cannot assign to 'id' u.name = "X"; // ok - In one paragraph, when does TS pay off and when is it overkill?
✨ Show Answer
Answer: TS is worth it for teams of 2+, codebases over a few thousand lines, libraries shipped to others, and any project that lives more than three months. It is overkill for one-off scripts, weekend prototypes, and tiny demos — the typing overhead exceeds the bug-catching benefit when the code lives an hour. Start in JS, switch to TS the moment the codebase outgrows your head.
Summary — Module 35
TypeScript is JS with a static type-checker. Types are erased at build time — zero runtime cost. Use interfaces or type aliases, generics for reusable shapes, narrowing for unions, and always turn on strict. Migrate one file at a time.