TypeScript logoTypeScript v5.0INTERMEDIATE

TypeScript

TypeScript cheat sheet covering types, interfaces, generics, utility types, type guards, and advanced type system features with examples.

12 min read
typescripttypesinterfacesgenericsjavascript

Basic Types

Primitive Types

TypeScript basic primitive types and type annotations

typescript
💡 Use unknown instead of any when possible
📌 const assertions create readonly literal types
✅ Enable strictNullChecks for better null safety

Type Aliases, Unions & Intersections

Create custom types with aliases, combine with unions and intersections

typescript
💡 Union (|) means "one of these" — intersection (&) means "all of these combined"
⚡ Literal types restrict values to exact strings, numbers, or booleans
📌 Intersections merge all properties — conflicting properties become never
🟢 Use type aliases for unions/intersections; use interfaces for object shapes you might extend

Enums

Named constants with numeric or string values

typescript
💡 String enums are preferred — they are readable in logs and don't have reverse mapping overhead
⚡ Use const enum to inline values at compile time — zero runtime cost
📌 Many teams prefer "as const" objects over enums — they are simpler and tree-shakable
🟢 keyof typeof MyEnum gives you a union of the enum key names as strings
enumconst-enum

Tuples & Readonly

Fixed-length typed arrays and immutable modifiers

typescript
💡 Tuples are arrays with fixed length and typed positions — great for return values
⚡ as const makes everything deeply readonly AND narrows to literal types
📌 readonly on arrays prevents push/pop/splice — the reference can still be reassigned
🟢 Named tuples (labels) improve readability but have no runtime effect
tuplereadonlyas-const

Functions

Function Types

Type annotations for functions and their parameters

typescript
💡 Use optional parameters instead of overloads when possible
📌 Arrow functions preserve lexical this
✅ Always type function parameters

Function Overloading

Define multiple function signatures for different parameter types

typescript
⚠️ Overload signatures must be compatible with implementation
💡 Order overloads from most specific to least specific
📌 Consider union types instead of overloads

Interfaces & Classes

Interfaces

Define object shapes and contracts for type checking

typescript
💡 Interfaces can be extended and merged
📌 Use interfaces for object shapes
✅ Prefer interfaces over type aliases for objects

Classes

Object-oriented programming with TypeScript classes

typescript
💡 Use parameter properties to reduce boilerplate
🔒 Private fields start with # in modern TS
📌 Abstract classes cannot be instantiated

Inheritance

Class inheritance and method overriding in TypeScript

typescript
💡 Use super() to call parent constructor
📌 Protected members accessible in derived classes
✅ Mixins provide multiple inheritance pattern

Generics

Generic Functions

Create reusable functions that work with multiple types

typescript
💡 TypeScript often infers generic types automatically
📌 Use constraints to limit generic types
✅ Generics make code reusable and type-safe

Generic Classes & Interfaces

Build flexible classes and interfaces with generic types

typescript
💡 Generic classes create type-safe data structures
📌 Static methods can have their own generic parameters
✅ Use generic constraints for type safety

Type Operations

Operators and assertions for querying and transforming types

Type Assertions (as, satisfies, as const)

Tell the compiler about types it cannot infer automatically

typescript
💡 satisfies validates WITHOUT widening — you keep literal types and autocomplete
⚡ as const is perfect for config objects, routes, and enum-like arrays
📌 Avoid "as" when possible — it overrides the compiler and hides real errors
🟢 typeof ARRAY[number] extracts a union of all values from an as const array
assatisfiesas-constassertion

keyof, typeof & Indexed Access

Query types from existing values and access type properties by key

typescript
💡 keyof + generics is the foundation for type-safe property access functions
⚡ typeof gets a type from a VALUE — essential for config objects and function return types
📌 T[K] indexed access works on nested types too: User["address"]["city"]
🟢 Array[number] extracts the element type from an array — combine with as const for unions
keyoftypeofindexed-access

Advanced Types

Utility Types

Built-in generic types for common type transformations

typescript
💡 Pick and Omit are your go-to for creating API response types from full models
⚡ Record<K, V> is cleaner than { [key: string]: V } for objects with known key types
📌 Exclude/Extract work on union types — Omit/Pick work on object types
🟢 ReturnType<typeof fn> extracts a function return type without writing it manually

Type Guards & Narrowing

All the ways to narrow types in conditional blocks

typescript
💡 Discriminated unions with a "kind" field + switch is the most type-safe branching pattern
⚡ Custom type predicates (is keyword) let you create reusable narrowing functions
📌 The assertNever pattern catches missing switch cases at compile time — essential for unions
🟢 TypeScript narrows automatically with typeof, instanceof, in, truthiness, and equality checks

Mapped, Conditional & Template Literal Types

Transform and construct types programmatically

typescript
💡 Mapped types are how Partial, Required, Readonly, and Record are built internally
⚡ Template literal types generate union combinations — perfect for CSS class builders
📌 infer extracts a type variable inside conditional types — powers ReturnType, Awaited, etc.
🟢 Key remapping with "as" + Capitalize builds getters, setters, and event handlers from shapes

Decorators

Stage 3 decorators for classes, methods, and properties (TypeScript 5+)

Decorators (TypeScript 5+)

Annotate and modify classes and their members with decorator functions

typescript
💡 TypeScript 5+ uses Stage 3 decorators — different API from the old experimentalDecorators
⚡ Decorator factories (functions returning decorators) let you pass config parameters
📌 Common in NestJS, Angular, and TypeORM — less common in React/frontend code
🟢 The context parameter tells you what is being decorated (method, field, class, accessor)
decoratorsclasstypescript-5

Modules & Namespaces

Imports & Exports

ES6 module syntax for importing and exporting code

typescript
💡 Use type-only imports for better tree-shaking
📌 Dynamic imports for code splitting
✅ Re-export to create public API

Declaration Files

Type declarations for JavaScript libraries and modules

typescript
💡 Use @types packages for library types
📌 .d.ts files contain only type declarations
✅ Declare modules for assets and untyped packages

TSConfig Reference

Compiler Options Reference

Complete reference of TypeScript compiler options with descriptions and values

typescript
💡 Start with strict: true and adjust as needed
📌 Use paths for clean import aliases
⚡ skipLibCheck speeds up compilation significantly
✅ Different project types need different configs