TypeScript Preview ADVANCED

JavaScript-এর উপর static type — ২০২০-এর industry default

~40 min Advanced 10 practice problems Live runner

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.

TypeScript = JavaScript + static type। Compile-time-এ চেক হয়, runtime-এ থাকে না। বড় কোডবেসে bug প্রায় অর্ধেকে নামিয়ে আনে — Microsoft ও Airbnb-র গবেষণা অনুসারে।

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):

first.js
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"]
}
Always use "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

  1. Add typescript as devDep, run tsc --init
  2. Set "allowJs": true and "checkJs": false initially
  3. Rename one .js at a time to .ts
  4. Sprinkle any where you don't have time — fix later
  5. Turn on "strict" when the surface is mostly typed
  6. Stop here — most apps thrive at 80% strict, not 100%

9. Glossary (শব্দকোষ)

TermMeaningবাংলায়
TypeScriptJS + a static type-checker. Erased at compile time.JS + static type checker; compile-এ types erase হয়।
tscThe TypeScript compiler.TypeScript compiler।
tsconfig.jsonCompiler 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 aliastype X = ... — a name for a type.Type-এর জন্য name দেওয়া।
InterfaceObject shape definition — extendable.Object shape — extend করা যায়।
UnionA | B — value can be one of several types.একাধিক type-এর যেকোনো একটি।
Genericfunction f<T> — type parameter for reusable shapes.Reusable shape-এর জন্য type parameter।
NarrowingRefining a union to a single type via guards.Guard দিয়ে union থেকে এক type-এ নামানো।
any / unknownDisable checks (avoid) / safe escape hatch (prefer).any avoid; unknown safer।
মনে রাখবেন: TypeScript Runtime cost free — types compile-এ erase হয়। বড় team বা library হলে অপরিহার্য; ছোট prototype-এ overkill। সবসময় strict on; boundary-তে unknown, ভেতরে narrow করে concrete type। Migration এক ফাইল করে — allowJs দিয়ে শুরু করুন।

10. Practice Problems

  1. Write a TS function signature for "add(a, b)" returning a number.
    ✨ Show Answer
    function add(a: number, b: number): number {
        return a + b;
    }
  2. Define an interface User with required name and optional email.
    ✨ Show Answer
    interface User {
        name: string;
        email?: string;
    }
  3. Define a Status union of three string literals.
    ✨ Show Answer
    type Status = "active" | "archived" | "draft";
  4. Write a generic identity function.
    ✨ Show Answer
    function id<T>(x: T): T { return x; }
  5. Show the JS-equivalent that would run in a browser sandbox.
    ✨ Show Answer
    a5.js
    const id = x => x;
    console.log(id(42), id("hi"));
  6. Why is unknown safer than any?
    ✨ Show Answer

    Answer: any opts out of all type checking — TS won't complain even if you call methods that don't exist. unknown says "I don't know yet" but forces you to narrow (typeof, instanceof, custom guard) before you use it. unknown at the boundary, types inside.

  7. 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;
    }
  8. Why turn on "strict": true?
    ✨ Show Answer

    Answer: Without it, you keep most of JavaScript's flexibility — and most of its bugs. strict turns 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.

  9. Show a readonly field 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
  10. 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.

TypeScript JS-এ static type যোগ করে। Runtime-এ cost নেই; bug-catching benefit বিশাল। বড় team বা library হলে অপরিহার্য।

Next Module → Performance — debounce, throttle, memoize।