Typescript Cheat Sheet

TypeScript is a strongly typed superset of JavaScript that provides optional static typing and other features to make writing and maintaining large-scale JavaScript applications easier. TypeScript is maintained by Microsoft and is used in many popular projects such as Angular, React, and Vue.js.

One of the main benefits of using TypeScript is that it provides additional type safety compared to JavaScript. With TypeScript, you can specify the types of variables, functions, and other objects, which helps catch errors at compile-time and provides better tooling and code completion in IDEs. Additionally, TypeScript has features such as interfaces and classes that allow for better code organization and maintainability.

For developers new to TypeScript or those looking for a quick reference, the cheat sheet above provides an overview of some of the most commonly used language features, syntax, and functions. The cheat sheet is divided into several sections, each with a table of related concepts and examples. The sections cover everything from basic types and syntax to more advanced features such as classes, interfaces, and generics.

Cheat Sheet

Table of Contents

  1. Basic Types
  2. Functions
  3. Interfaces
  4. Classes
  5. Enums
  6. Type Inference
  7. Type Aliases
  8. Union Types
  9. Intersection Types
  10. Type Guards
  11. Generics
  12. Type Assertions
  13. Modules
  14. Decorators

1. Basic Types

TypeDescriptionExample
numberRepresents numeric valueslet count: number = 5;
stringRepresents textual valueslet message: string = “Hello, world!”;
booleanRepresents logical valueslet isDone: boolean = false;
nullRepresents the absence of any valuelet data: null = null;
undefinedRepresents a value that has not been initializedlet data: undefined = undefined;
voidRepresents the absence of a valuefunction logMessage(message: string): void { console.log(message); }
anyRepresents any valuelet data: any = “hello”;
neverRepresents a value that will never occurfunction raiseError(): never { throw new Error(“Something went wrong!”); }

2. Functions

SyntaxDescriptionExample
Function DeclarationDefines a named functionfunction add(x: number, y: number): number { return x + y; }
Function ExpressionDefines a function expression that can be assigned to a variableconst add = function(x: number, y: number): number { return x + y; };
Arrow Function ExpressionDefines a function expression using the arrow syntaxconst add = (x: number, y: number): number => { return x + y; };

3. Interfaces

SyntaxDescriptionExample
Interface DeclarationDefines a new interfaceinterface Person { name: string; age: number; }
Optional PropertiesDefines optional propertiesinterface Person { name: string; age?: number; }
Readonly PropertiesDefines read-only propertiesinterface Point { readonly x: number; readonly y: number; }
Index SignaturesDefines an index signature to allow any property nameinterface Dictionary { [key: string]: any; }

4. Classes

SyntaxDescriptionExample
Class DeclarationDefines a new classclass Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } }
InheritanceDefines a class that inherits from another classclass Employee extends Person { department: string; constructor(name: string, age: number, department: string) { super(name, age); this.department = department; } }
Access ModifiersDefines public, private, and protected access modifiers for class membersclass Person { public name: string; private age: number; protected phone: string; constructor(name: string, age: number, phone: string) { this.name = name; this.age = age; this.phone = phone; } }
Abstract ClassesDefines abstract classes that cannot be instantiatedabstract class Animal { abstract makeSound(): void; }

5. Enums

SyntaxDescriptionExample
Enum DeclarationDefines a new enumenum Color { Red, Green, Blue }
Enum ValuesSpecifies numeric values for enum membersenum Color { Red = 1, Green = 2, Blue = 3 }
String EnumsSpecifies string values for enum membersenum Color { Red = “RED”, Green = “GREEN”, Blue = “BLUE” }
Computed EnumsSpecifies computed values for enum membersenum Color { Red = 1, Green = 2, Blue = 3, Yellow = Red + Green }

6. Type Inference

SyntaxDescriptionExample
Basic Type InferenceInfers types based on assigned valueslet count = 5; // count is inferred as number
Best Common TypeInfers the best common type of a set of valueslet values = [1, 2, true]; // values is inferred as (number | boolean)[]
Contextual TypingInfers types based on their contextlet handler = (event: MouseEvent) => { console.log(event.clientX); };

7. Type Aliases

SyntaxDescriptionExample
Type Alias DeclarationDefines a new type aliastype Point = { x: number; y: number; };
Union Type AliasesDefines a union of types as a new type aliastype ID = string | number;
Intersection Type AliasesDefines an intersection of types as a new type aliastype Employee = Person & { department: string; };

8. Union Types

SyntaxDescriptionExample
Union TypesDefines a type that can be one of several typeslet value: string | number;
Type GuardsUses typeof, instanceof, or custom checks to narrow union typesfunction isNumber(value: string | number): value is number { return typeof value === “number”; } if (isNumber(value)) { // value is narrowed to number }

9. Intersection Types

SyntaxDescriptionExample
Intersection TypesDefines a type that is a combination of several typestype Employee = Person & { department: string; }; let employee: Employee = { name: “John”, age: 30, department: “IT” };

10. Type Guards

SyntaxDescriptionExample
typeof Type GuardsUses typeof to narrow typeslet value: string | number; if (typeof value === “string”) { // value is narrowed to string }
instanceof Type GuardsUses instanceof to narrow typesfunction isAnimal(value: any): value is Animal { return value instanceof Animal; } if (isAnimal(value)) { // value is narrowed to Animal }
Custom Type GuardsDefines custom functions to narrow typesfunction isNumber(value: string | number): value is number { return typeof value === “number”; } if (isNumber(value)) { // value is narrowed to number }

11. Generics

SyntaxDescriptionExample
Generic Type ParametersDefines a generic type parameterfunction identity<T>(value: T): T { return value; }
Generic ConstraintsDefines constraints on generic type parametersfunction getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }
Generic Classes (continued)Defines a generic classclass Queue<T> { private items: T[] = []; push(item: T) { this.items.push(item); } pop(): T | undefined { return this.items.shift(); } }
Default Type ParametersDefines default types for generic type parametersfunction identity<T = any>(value: T): T { return value; }
Generic Utility TypesProvides built-in generic utility typestype Partial<T> = { [P in keyof T]?: T[P]; }; type Readonly<T> = { readonly [P in keyof T]: T[P]; }; type Record<K extends keyof any, T> = { [P in K]: T };

12. Type Assertions

SyntaxDescriptionExample
Type AssertionsAsserts a type on a valuelet value: any = “hello”; let length: number = (value as string).length;
Non-null Assertion OperatorAsserts a value is not null or undefinedlet value: string | null = “hello”; let length: number = value!.length;

13. Modules

SyntaxDescriptionExample
Import DeclarationsImports code from other modulesimport { MyComponent } from “./my-component”;
Export DeclarationsExports code from a moduleexport function myFunction() { /* … */ }
Default ExportsExports a default value from a moduleexport default class MyComponent { /* … */ }
Namespace ImportsImports all exported values from a module into a namespaceimport * as myModule from “./my-module”;

14. Decorators

SyntaxDescriptionExample
Class DecoratorsDecorates a class@myDecorator class MyClass { /* … */ }
Method DecoratorsDecorates a methodclass MyClass { @myDecorator myMethod() { /* … */ } }
Property DecoratorsDecorates a propertyclass MyClass { @myDecorator myProperty: string; }
Parameter DecoratorsDecorates a parameterclass MyClass { myMethod(@myDecorator arg: string) { /* … */ } }

Reference:

https://www.typescriptlang.org/docs/