Programmer’s Reference
TypeScript Learn JavaScript control flow with types, interfaces, and compile-time checks.
TypeScript 5+; satisfies requires 4.9+. Type annotations are erased during compilation and do not validate external data at runtime. Code examples are independent .ts files, checked with strict mode and an ES2020 target.
20 entries · Essentials first · Reviewed October 5, 2026
Keywords and types const / let / type annotations # Declare variables and optionally specify their types.
TypeScript code Copy
const displayName: string = 'Demo';
let count: number = 0;
const ready: boolean = true;
count += 1;
console.log(displayName, count, ready);Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes Use lowercase string, number, and boolean. const prevents reassignment, not mutation inside objects.
Source: www.typescriptlang.org documentation
Branch on a condition; typeof checks can narrow a union type.
TypeScript code Copy
function label(value: string | number): string {
if (typeof value === 'number') {
return value.toFixed(0);
} else {
return value.toUpperCase();
}
}
console.log(label(3));Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes A type annotation is not a runtime check. typeof null is "object".
Source: www.typescriptlang.org documentation
Use short-circuit boolean logic inherited from JavaScript.
TypeScript code Copy
const nickname: string = '';
const label = nickname || 'Guest';
const ready: boolean = true;
if (ready && !nickname) { console.log(label); }Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes || returns an operand, not necessarily a boolean. Zero and empty strings are falsey.
Source: www.typescriptlang.org documentation
?? / ?. / null / undefined # Use optional chaining for a missing object and nullish coalescing for a fallback.
TypeScript code Copy
function display(user: { name?: string } | undefined): string {
return user?.name ?? 'Guest';
}
console.log(display(undefined));Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes ?? preserves zero and empty strings. Optional chaining does not make every subsequent property access safe.
Source: www.typescriptlang.org documentation
Repeat work with JavaScript loop syntax and typed values.
TypeScript code Copy
const names: string[] = ['Demo', 'Example'];
for (const name of names) { console.log(name); }
for (let i = 0; i < names.length; i++) { console.log(i); }
let remaining = 2;
while (remaining > 0) { remaining--; }Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes for...in visits property keys, while for...of visits iterable values. Avoid infinite loops.
Source: www.typescriptlang.org documentation
Exit the enclosing loop or skip its current iteration.
TypeScript code Copy
for (let n = 0; n < 5; n++) {
if (n === 1) { continue; }
if (n === 3) { break; }
console.log(n);
}Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes break does not return from a function; continue requires a loop.
Source: www.typescriptlang.org documentation
function / return / void # Describe function inputs and output; void means no useful returned value.
TypeScript code Copy
function doubleValue(n: number): number { return n * 2; }
function report(message: string): void { console.log(message); }
report(String(doubleValue(3)));Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes A return annotation is checked at compile time; it does not convert values.
Source: www.typescriptlang.org documentation
type / union / literal types # Give a type a reusable name and restrict values to alternatives.
TypeScript code Copy
type State = 'ready' | 'waiting';
type Identifier = string | number;
const state: State = 'ready';
const id: Identifier = 7;
console.log(state, id);Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes A type alias does not create a runtime value. Narrow unions before using type-specific methods.
Source: www.typescriptlang.org documentation
interface / optional properties / readonly # Describe an object shape, including optional and read-only properties.
TypeScript code Copy
interface Item {
readonly id: number;
name: string;
note?: string;
}
const item: Item = { id: 1, name: 'Demo' };
console.log(item.note ?? 'No note');Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes readonly is a type-checking restriction, not a runtime freeze. Optional properties may be undefined.
Source: www.typescriptlang.org documentation
Type a variable-length array or a fixed-position tuple.
TypeScript code Copy
const names: Array<string> = ['Demo'];
const counts: number[] = [1, 2];
const pair: [string, number] = ['Demo', 2];
console.log(names, counts, pair);Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes [number] is a one-element tuple, not a general array. Runtime arrays can still contain invalid external data.
Source: www.typescriptlang.org documentation
unknown requires narrowing before use; any disables most type checking.
TypeScript code Copy
function describe(value: unknown): string {
return typeof value === 'string' ? value.toUpperCase() : 'Not text';
}
console.log(describe('Demo'));Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes Prefer unknown for untrusted values. Neither unknown nor any validates a JSON schema.
Source: www.typescriptlang.org documentation
Tell the compiler how to treat a value without changing it.
TypeScript code Copy
const value: unknown = 'Demo';
const text = value as string;
console.log(text.toUpperCase());Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes Assertions do not validate or convert values; this succeeds only because the example value really is a string.
Source: www.typescriptlang.org documentation
Preserve a relationship between input and output types.
TypeScript code Copy
function first<T>(values: T[]): T | undefined {
return values[0];
}
const result = first<string>(['Demo']);
console.log(result);Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes An array may be empty, so this return type includes undefined.
Source: www.typescriptlang.org documentation
keyof / indexed access types # Restrict keys to an object type and derive the corresponding value type.
TypeScript code Copy
function get<T, K extends keyof T>(object: T, key: K): T[K] {
return object[key];
}
console.log(get({ name: 'Demo', count: 3 }, 'name'));Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes keyof is a type-level operation; Object.keys returns runtime strings with different guarantees.
Source: www.typescriptlang.org documentation
Check compatibility while retaining a useful inferred type; as const preserves literal values.
TypeScript code Copy
const settings = { mode: 'ready', retries: 3 } as const satisfies {
mode: 'ready' | 'waiting';
retries: number;
};
console.log(settings.mode);Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes satisfies requires TypeScript 4.9+ and does not perform runtime validation.
Source: www.typescriptlang.org documentation
Narrow a discriminated union and check that every variant is handled.
TypeScript code Copy
type Result = { kind: 'ok'; value: number } | { kind: 'error'; message: string };
function describe(result: Result): string {
switch (result.kind) {
case 'ok': return String(result.value);
case 'error': return result.message;
default: { const unreachable: never = result; return unreachable; }
}
}
console.log(describe({ kind: 'ok', value: 3 }));Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes Keep a literal discriminator on each variant. Adding a variant requires updating exhaustive switches.
Source: www.typescriptlang.org documentation
async / await / Promise<T> # Express asynchronous results with a typed promise.
TypeScript code Copy
async function getCount(): Promise<number> { return 3; }
async function main(): Promise<void> {
const count = await getCount();
console.log(count);
}
void main().catch(console.error);Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes await requires an async function or a compatible top-level module setting; handle promise rejection.
Source: www.typescriptlang.org documentation
TypeScript has no goto statement; use structured branches, loops, and functions.
TypeScript code Copy
function describe(ready: boolean): string {
if (ready) { return 'Ready'; }
return 'Waiting';
}
console.log(describe(true));Practical use Practice in a standalone example file before using this pattern in your project.
Common mistakes TypeScript uses JavaScript control-flow syntax; labels are not goto targets.
Source: www.typescriptlang.org documentation