TypeScript

Quickstart (init + run)

bash
mkdir my-ts && cd my-ts
npm init -y
npm i -D typescript tsx
npx tsc --init
printf 'console.log("hi")\n' > index.ts
npx tsx index.ts

Project setup (tsconfig basics)

json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "skipLibCheck": true
  }
}

Type + function

typescript
type User = { id: string; email: string };

export function toEmail(u: User): string {
  return u.email;
}

Narrowing

typescript
function isError(x: unknown): x is Error {
  return x instanceof Error;
}

Variables (type annotations)

typescript
let n: number = 1;
const ok: boolean = true;
const tags: string[] = ["a", "b"];
const rec: Record<string, number> = { a: 1 };

Datatypes (union + literal + enum)

typescript
type Status = "idle" | "loading" | "error";

enum Role {
  Admin = "admin",
  User = "user",
}

Iteration (arrays + maps)

typescript
const xs: number[] = [1, 2, 3];
for (const x of xs) console.log(x);

const m = new Map<string, number>([["a", 1]]);
for (const [k, v] of m) console.log(k, v);

Functions (generics)

typescript
function first<T>(xs: T[]): T | undefined {
  return xs[0];
}

Interfaces + classes

typescript
interface Logger {
  log(msg: string): void;
}

class ConsoleLogger implements Logger {
  log(msg: string) {
    console.log(msg);
  }
}

Optional chaining + nullish coalescing

typescript
type User = { profile?: { name?: string } };
const u: User = {};
const name = u.profile?.name ?? "Anonymous";