class User {
constructor(public id: number, public name: string) {}
}Parameter properties create and assign fields directly from constructor parameters.
Classes, access modifiers, inheritance, modules, and validation boundaries.
Class fields, constructors, access modifiers, and inheritance.
class User {
constructor(public id: number, public name: string) {}
}Parameter properties create and assign fields directly from constructor parameters.
class Counter {
private value = 0;
increment() {
this.value += 1;
}
}Access modifiers are checked at compile time and influence editor API surface.
class Config {
readonly env: string;
constructor(env: string) {
this.env = env;
}
}Readonly is useful for IDs, config values, and immutable domain objects.
class Animal {
move() {
return "moving";
}
}
class Bird extends Animal {
fly() {
return "flying";
}
}Inheritance works well for simple hierarchies, though composition is often easier to maintain.
abstract class Repository<T> {
abstract findById(id: string): T | undefined;
}Abstract classes are useful when shared implementation and a contract both matter.
class Temperature {
private celsius = 0;
get fahrenheit() {
return this.celsius * 1.8 + 32;
}
set fahrenheit(value: number) {
this.celsius = (value - 32) / 1.8;
}
}Getters and setters let APIs expose properties while keeping internal conversions hidden.
ES modules, type-only imports, and export patterns.
export function add(a: number, b: number) {
return a + b;
}
export const APP_NAME = "CheatSheet";Named exports scale well when a module exposes several helpers.
export default function formatCurrency(value: number) {
return `$${value.toFixed(2)}`;
}Default exports are common, but many teams prefer named exports for consistency.
import type { User } from "./types";Type-only imports help avoid accidental runtime dependencies and can improve clarity.
export { add, subtract } from "./math";
export type { MathOptions } from "./types";Barrel files can simplify imports, but use them thoughtfully to avoid confusing dependency graphs.
const module = await import("./heavy-module");Dynamic imports are useful for code splitting and conditional loading.
Handle unknown inputs safely and validate external data.
const raw: unknown = JSON.parse(payload);Using `unknown` forces validation before use and is safer than blindly asserting types.
try {
riskyWork();
} catch (error: unknown) {
if (error instanceof Error) {
console.error(error.message);
}
}Catches should treat errors as unknown at boundaries and narrow deliberately.