Getting Started
5 snippetsYour first steps with TypeScript basics
Hello World
console.log("Hello, World!"); Type Annotation
let name: string = "John";
let age: number = 25; Type Inference
let name = "John"; // inferred as string
let count = 0; // inferred as number Compile
tsc file.ts // Compile to JS
tsc --watch // Watch mode Strict Mode
// tsconfig.json
{ "compilerOptions": { "strict": true } } Basic Types
8 snippetsType annotations for variables
String
let name: string = "John"; Number
let age: number = 25; Boolean
let isActive: boolean = true; Array
let nums: number[] = [1, 2, 3];
let strs: Array<string> = ["a", "b"]; Tuple
let tuple: [string, number] = ["age", 25]; Any
let data: any = "anything"; Unknown
let value: unknown = getValue(); Void/Never
function log(msg: string): void {}
function fail(): never { throw new Error(); } Operators
6 snippetsType operators and assertions
Type Assertion
const len = (value as string).length;
const len = (<string>value).length; Non-null Assertion
const el = document.getElementById("id")!;
el.textContent = "Hello"; Optional Chaining
obj?.property
obj?.method?.()
arr?.[index] Nullish Coalescing
const name = value ?? "default";
let x = 0;
x ??= 10; // x stays 0 Satisfies
const config = {
port: 3000,
} satisfies Config; Keyof/Typeof
type Keys = keyof User; // "name" | "age"
type UserType = typeof user; Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Loops
7 snippetsRepeat code with type safety
For
for (let i = 0; i < 5; i++) {
console.log(i);
} For...of (Arrays)
for (const item of array) {
console.log(item);
} For...in (Objects)
for (const key in object) {
console.log(key, object[key]);
} ForEach (Typed)
const nums: number[] = [1, 2, 3];
nums.forEach((n: number) => console.log(n)); While
while (count < 10) {
count++;
} Map with Types
const doubled: number[] = nums.map(
(n: number): number => n * 2
); Reduce with Types
const sum: number = nums.reduce(
(acc: number, n: number) => acc + n, 0
); Interfaces & Types
5 snippetsDefine custom type shapes
Interface
interface User {
name: string;
age: number;
email?: string; // optional
} Type Alias
type ID = string | number; Union
type Status = "pending" | "approved" | "rejected"; Intersection
type Employee = Person & { employeeId: number }; Extends
interface Admin extends User {
permissions: string[];
} Functions
4 snippetsTyped functions and callbacks
Typed Function
function greet(name: string): string {
return `Hello, ${name}!`;
} Arrow Function
const add = (a: number, b: number): number => a + b; Optional Param
function greet(name?: string): string {
return `Hello, ${name ?? "World"}!`;
} Function Type
type Callback = (data: string) => void; Generics
4 snippetsReusable type-safe components
Generic Function
function identity<T>(arg: T): T {
return arg;
} Generic Interface
interface Box<T> {
value: T;
} Constraints
function getLength<T extends { length: number }>(arg: T): number {
return arg.length;
} Multiple Types
function pair<K, V>(key: K, value: V): [K, V] {
return [key, value];
} Utility Types
12 snippetsBuilt-in type transformations
Partial
type PartialUser = Partial<User>;
// All properties optional
// { name?: string; age?: number; } Required
type RequiredUser = Required<User>;
// All properties required Pick
type NameOnly = Pick<User, "name" | "age">;
// Only selected properties Omit
type NoEmail = Omit<User, "email">;
// All except listed properties Record
type UserMap = Record<string, User>;
type StatusMap = Record<"pending" | "done", number>; Readonly
type ReadonlyUser = Readonly<User>;
// All properties readonly Exclude
type T = Exclude<"a" | "b" | "c", "a">;
// "b" | "c" Extract
type T = Extract<"a" | "b" | "c", "a" | "f">;
// "a" NonNullable
type T = NonNullable<string | null | undefined>;
// string ReturnType
function getUser() { return { name: "John" }; }
type User = ReturnType<typeof getUser>; Parameters
function greet(name: string, age: number) {}
type P = Parameters<typeof greet>;
// [string, number] Awaited
type A = Awaited<Promise<string>>;
// string Classes
3 snippetsObject-oriented programming patterns
Class
class Dog {
constructor(public name: string) {}
bark(): string {
return `${this.name} says woof!`;
}
} Private/Public
class User {
private password: string;
public name: string;
} Abstract
abstract class Animal {
abstract speak(): void;
} Advanced Types
7 snippetsComplex type manipulations
Type Guard
function isString(x: unknown): x is string {
return typeof x === "string";
}
if (isString(value)) {
value.toUpperCase(); // TS knows it's string
} Discriminated Unions
type Result =
| { status: "success"; data: string }
| { status: "error"; error: Error };
function handle(r: Result) {
if (r.status === "success") {
console.log(r.data); // TS knows data exists
}
} As Const
const colors = ["red", "green"] as const;
// readonly ["red", "green"]
const config = {
port: 3000,
host: "localhost"
} as const; Template Literal Types
type Event = "click" | "focus";
type Handler = `on${Capitalize<Event>}`;
// "onClick" | "onFocus" Mapped Types
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number; } Conditional Types
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false Infer Keyword
type UnwrapPromise<T> =
T extends Promise<infer U> ? U : T;
type A = UnwrapPromise<Promise<string>>; // string
type B = UnwrapPromise<number>; // number