
- TypeScript - Home
- TypeScript - Roadmap
- TypeScript - Overview
- TypeScript - Environment Setup
- TypeScript - Basic Syntax
- TypeScript vs. JavaScript
- TypeScript - Features
- TypeScript - Variables
- TypeScript - let & const
- TypeScript - Operators
- TypeScript - Types
- TypeScript - Type Annotations
- TypeScript - Type Inference
- TypeScript - Numbers
- TypeScript - Strings
- TypeScript - Boolean
- TypeScript - Arrays
- TypeScript - Tuples
- TypeScript - Enums
- TypeScript - Any
- TypeScript - Never
- TypeScript - Union
- TypeScript - Literal Types
- TypeScript - Symbols
- TypeScript - null vs. undefined
- TypeScript - Type Aliases
- TypeScript Control Flow
- TypeScript - Decision Making
- TypeScript - If Statement
- TypeScript - If Else Statement
- TypeScript - Nested If Statements
- TypeScript - Switch Statement
- TypeScript - Loops
- TypeScript - For Loop
- TypeScript - While Loop
- TypeScript - Do While Loop
- TypeScript Functions
- TypeScript - Functions
- TypeScript - Function Types
- TypeScript - Optional Parameters
- TypeScript - Default Parameters
- TypeScript - Anonymous Functions
- TypeScript - Function Constructor
- TypeScript - Rest Parameter
- TypeScript - Parameter Destructuring
- TypeScript - Arrow Functions
- TypeScript Interfaces
- TypeScript - Interfaces
- TypeScript - Extending Interfaces
- TypeScript Classes and Objects
- TypeScript - Classes
- TypeScript - Objects
- TypeScript - Access Modifiers
- TypeScript - Readonly Properties
- TypeScript - Inheritance
- TypeScript - Static Methods and Properties
- TypeScript - Abstract Classes
- TypeScript - Accessors
- TypeScript - Duck-Typing
- TypeScript Advanced Types
- TypeScript - Intersection Types
- TypeScript - Type Guards
- TypeScript - Type Assertions
- TypeScript Type Manipulation
- TypeScript - Creating Types from Types
- TypeScript - Keyof Type Operator
- TypeScript - Typeof Type Operator
- TypeScript - Indexed Access Types
- TypeScript - Conditional Types
- TypeScript - Mapped Types
- TypeScript - Template Literal Types
- TypeScript Generics
- TypeScript - Generics
- TypeScript - Generic Constraints
- TypeScript - Generic Interfaces
- TypeScript - Generic Classes
- TypeScript Miscellaneous
- TypeScript - Triple-Slash Directives
- TypeScript - Namespaces
- TypeScript - Modules
- TypeScript - Ambients
- TypeScript - Decorators
- TypeScript - Type Compatibility
- TypeScript - Date Object
- TypeScript - Iterators and Generators
- TypeScript - Mixins
- TypeScript - Utility Types
- TypeScript - Boxing and Unboxing
- TypeScript - tsconfig.json
- From JavaScript To TypeScript
- TypeScript Useful Resources
- TypeScript - Quick Guide
- TypeScript - Cheatsheet
- TypeScript - Useful Resources
- TypeScript - Discussion
TypeScript Cheatsheet
This TypeScript cheatsheet provides a concise reference to key TypeScript concepts, including types, functions, interfaces, and classes. It covers advanced topics such as generics, decorators, and type compatibility, with practical code examples for each feature. It is designed to help developers quickly understand and apply TypeScript's type system and object-oriented programming principles. Use this guide as a fast resource for writing efficient and type-safe code in TypeScript.
Table of Contents
- About
- Basic Types
- Any, Void, and Others
- Arrays and Tuples
- Union and Intersection Types
- Special Types
- Enums
- Type Guards
- Discriminated Unions
- Mapped Types
- Utility Types
- Never Type
- Declarations
- Variables
- Functions
- Type Assertions
- Interfaces
- Type Aliases
- Function Types
- Classes
- Generics
- Modules
- Advanced Types
- Literal Types
- Decorators
- Type Compatibility
- Structural Typing
About
TypeScript is a language extension to JavaScript, which uses static types. It advances development vigor by implementing type safety, advocating computability of larger JavaScript applications, and eliminating certain errors at compile time, instead of run time.
Basic Types
Common primitive types such as boolean, number, and string. These are the building blocks of a TypeScript application.
boolean, number, string: Common primitive types.
null, undefined: Absence of a value.
bigint, symbol: Special types for larger integers and unique values.
Any, Void, and Others
Special types such as any, void, and others that handle specific use cases in TypeScript.
any: Disables type-checking for the variable.
void: Represents no value (typically for functions that dont return anything).
Arrays and Tuples
Working with ordered collections of data like arrays and tuples.
Arrays: Use type[] or Array<type>.
Tuples: Define ordered sets of types, e.g., [string, number].
Union and Intersection Types
Union and intersection types to handle multiple possible types or combine multiple types.
Union Types: string | null | undefined.
Intersection Types: Combines multiple types into one.
Special Types
Specialized types such as never, unknown, and enum to handle unique cases.
never: Indicates unreachable code.
unknown: A safer alternative to any.
enum: Allows creation of named constants.
Enums
Enums allow for creating named constants, either numeric or string-based.
Type | Description | Code Example |
Numeric Enum | Automatically assigned numeric values. | enum Direction { Up = 1, Down, Left, Right } |
String Enum | Explicitly assign string values. | enum Status { Success = 'SUCCESS', Error = 'ERROR' } |
Type Guards
Techniques for narrowing down types during runtime.
Type | Description | Code Example |
typeof Guard | Checks the type of a variable. | function print(value: string | number) { ... } |
instanceof | Check if an object is an instance. | if (date instanceof Date) { ... } |
Custom Guard | Function that returns value is Type. | function isString(value: unknown): value is string { ... } |
Discriminated Unions
Using discriminated unions to narrow types based on a shared property.
Description | Code Example |
Discriminant Property for Narrowing | type Shape = { kind: 'circle', radius: number } |
Mapped Types
Mapped types allow you to transform the properties of a type.
Mapped Type | Description | Code Example |
Partial<T> | Makes all properties optional. | type PartialUser = Partial<{ name: string; age: number }> |
Required<T> | Makes all properties required. | type RequiredUser = Required<PartialUser> |
Readonly<T> | Makes all properties read-only. | type ReadonlyUser = Readonly<{ name: string; age: number }> |
Utility Types
Utility types provide common transformations to work with types.
Utility Type | Description | Code Example |
Pick<T, K> | Selects specific keys from a type. | type NameOnly = Pick<User, 'name'> |
Omit<T, K> | Excludes specific keys from a type. | type NoName = Omit<User, 'name'> |
Record<K, T> | Creates an object type with keys. | type Dictionary = Record<string, number> |
Extract<T, U> | Extracts types from T assignable to U. | type Extracted = Extract<'a' | 'b', 'a'> |
Exclude<T, U> | Excludes types from T assignable to U. | type Excluded = Exclude<'a' | 'b', 'a'> |
Never Type
The never type represents values that will never occur. It is used in cases like function signatures that never return or infinite loops.
Description | Code Example |
Unreachable Code: | function fail(message: string): never { throw new Error(message); } |
Exhaustiveness Check: | function check(value: 'a' | 'b') { ... } |
Declarations
Declarations define variables, functions, classes, and other entities in TypeScript.
Variables: Variables are used to store data and can be assigned types explicitly or inferred automatically.
let isDone: boolean; let isDone: boolean = false;
Functions: Functions in TypeScript can be typed to ensure parameters and return values are consistent.
function add(a: number, b: number): number { return a + b; }
Type Assertions: Type assertions are used to tell the compiler to treat a value as a specific type.
let len: number = (input as string).length;
Interfaces
Interfaces are used to define the shape of an object, specifying which properties and methods it must have.
Inline Interfaces: Define interfaces directly within the function parameter for simple structures.
function printLabel(options: { label: string }) { ... }
Explicit Interfaces: Declare a separate interface to specify the structure of the parameter object.
interface LabelOptions { label: string; }
Optional Properties: Define properties that are not required in an interface, using the "?" symbol.
interface User { name: string; age?: number; }
Read-only Properties: Define properties that cannot be modified after being initialized, using the read-only keyword.
interface User { readonly name: string; }
Dynamic Keys: Use index signatures to define object keys that can be dynamically assigned.
{ [key: string]: Object[] }
Type Aliases
Type aliases are used to create new names for types, including unions, intersections, and other complex types.
Aliases: Combine multiple types or data structures under a single alias.
type Name = string | string[];
Intersections: Combine multiple types into one by requiring all properties of both.
type ColorfulCircle = Colorful & Circle;
Function Types
Function types define the signature of a function, including the types of the parameters and return values.
function getUser(callback: (user: User) => any) { callback({...}); }
Classes
Classes in TypeScript are used to define objects with properties and methods.
Basic Structure: Define a class with a constructor and instance properties.
class Point { x: number; y: number; static instances = 0; constructor(x: number, y: number) { this.x = x; this.y = y; } }
Inheritance: Extend a class to inherit its properties and methods.
class Point3D extends Point { ... }
Generics
Generics: Generics allow you to write reusable and type-safe code by allowing types to be passed as parameters.
class Greeter<T> { greeting: T; constructor(message: T) { this.greeting = message; } }
Modules
Modules: Modules allow you to organize your code into reusable pieces. They can export functions, objects, and variables and import them into other files.
export interface User { ... }
Advanced Types
Advanced types in TypeScript include conditional types, infer types and template literal types.
Type Extraction: Extract specific types from existing types.
type Walls = Building['room']['walls'];
Keyof Type Operator: Create a type that consists of all keys of an object type.
type P = keyof Point; // x | y
Conditional Types: Define types based on conditions using extends.
type ToArray<T> = T extends any ? T[] : never;
Inferring Types: Extract return types from functions using conditional types.
type GetReturnType<T> = T extends (...args: unknown[]) => infer R ? R : never;
Literal Types
Literal Types: Literal types allow you to specify exact values for a variable or parameter instead of a broader type.
const literalPoint = { x: 4, y: 2 } as const;
Template Literal Types: Decorators are special functions that can modify classes, methods, or properties. They are often used in frameworks like Angular.
type TrimLeft<S extends string> = S extends `${SpaceChar}${infer Rest}` ? TrimLeft<Rest> : S;
Decorators
The table given below explains the types of decorators along with examples:
Type | Description | Code Example |
Class Decorator | Adds metadata to a class. | function Logger(target: Function) { ... } @Logger class MyClass {} |
Property Decorator | Adds metadata to class properties. | function Readonly(target: any, key: string) { ... } class User { @Readonly name = 'John'; } |
Type Compatibility and Structural Typing
Type Compatibility and Structural Typing | Explanation | Code Example |
Structural Typing | A type is compatible if it has the same structure. | type Point = { x: number; y: number; }; type Coordinate = { x: number; y: number; }; const point: Point = { x: 10, y: 20 }; const coordinate: Coordinate = point; // Compatible |
Function Compatibility | Function parameters are checked structurally. | type Callback = (a: number, b: number) => number; const add: Callback = (x, y) => x + y; function executeCallback(cb: Callback, a: number, b: number): number { return cb(a, b); } executeCallback(add, 5, 10); |