TypeScript logo

TypeScript Cheat Sheet

For TypeScript v3.9+

Types
Primitives
Boolean True or false
Number Decimal, hex, binary, or ocatal
String "string" or 'string' or `string`
Null Absense of a value
Undefined myVar name; // Undefined
bigint Very large integers
symbol Creates a globally unique reference
Symbol("s") !== Symbol("s");
Others
Array type[] = [val1, val2, …], or
Array<type> = [val1, val2, …]
Tuple let x: [type1, type2, …]
Enum enum Numbers {One = 1, …} Numbers.One === 1; // true, or
enum Strings {One = "one", …}
Any Opt-out of type checking; value passes compile-time checks
let unknown: any;
Void Opposite of any: absence of any type
function nothing(): void {}
Never Represents type of values that never occur
Object Non-primitive type
Concepts
Primitive types String, number, boolean, etc.
Type inference let name = 'Fluffy';
first = 1234; // Error
Shape of an object TypeScript knows and enforces the properties of objects.
Type annotations let myVariable: type;
Type assertions x!.toString(); // Stating that x is the right type
strictNullChecks Enforces using null and undefined explicitly.
Namespaces Organise code by wrapping variables, classes, etc. together.
Narrowing Validation that ensures variables are a particular type.
Declarations
Variables let isDone: boolean = false;
Literals const pi = 3.14; // π
Untion types let age: string | number;
Type guards
Primitive if (typeof padding === "number") {}
User-defined isFish(pet: Fish | Bird): pet is Fish => {
   return (pet as Fish).swim !== undefined;
}
if (isFish(pet)) {}
Functions
Argument type function myFn (arg: type) {}
Return type function myFn (arg): type {}
Arrow form myFn (arg: type): type => {}
Interfaces
Explicit interface Options {
   x: number;}
Inline myFn (opts: {x: number}) => {}
Optional propertiesinterface Options {
   x?: number;}
Readonly propertiesinterface Options {
   readonly x: number;}
Mapped typestype Dynamic {
   [key: string]: type;}
Generics
Basic declaration function id<Type>(arg: Type): Type {return arg;}
Calling it explicity id<string>("hi");
Calling it, inferred id("hi"); // returns "hi"
Unique name function id<primitive>(arg: primitive): primitive {return arg;}
Interface interface GenericIdentityFns { <Type>(arg: Type): Type;}
Generic constraints interface Numeric {
   length: number;}
function myFn<Type extends Numeric>(arg: Type) {}
Type parameters in generic constraints function<Type, Key extends keyof Type>(…) {}
Namespaces
Basic example namespace helpers {
   function isValid(a: string) {}
}
helpers.isValid("hi");
Multi-file namespaces /// <reference path="Validation.ts" />
Aliases import Triangles = Shapes.Polygons.Triangles;
Operators
keyof type operator type Point = {x: number};
type keyType = keyof Point;
typeof type operator let greet = "hello";
let hi: typeof greet;