TypeScript documentation
Official TypeScript handbook (types, narrowing, generics, config).
Official TypeScript handbook (types, narrowing, generics, config).
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
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true
}
}
type User = { id: string; email: string };
export function toEmail(u: User): string {
return u.email;
}
function isError(x: unknown): x is Error {
return x instanceof Error;
}
let n: number = 1;
const ok: boolean = true;
const tags: string[] = ["a", "b"];
const rec: Record<string, number> = { a: 1 };
type Status = "idle" | "loading" | "error";
enum Role {
Admin = "admin",
User = "user",
}
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);
function first<T>(xs: T[]): T | undefined {
return xs[0];
}
interface Logger {
log(msg: string): void;
}
class ConsoleLogger implements Logger {
log(msg: string) {
console.log(msg);
}
}
type User = { profile?: { name?: string } };
const u: User = {};
const name = u.profile?.name ?? "Anonymous";