DEV Community

Cover image for TypeScript Cheat Sheet πŸ“„ (32 Code Examples + PDF & Poster)
Danny Adams
Danny Adams

Posted on • Edited on • Originally published at doabledanny.com

TypeScript Cheat Sheet πŸ“„ (32 Code Examples + PDF & Poster)

I recently wrote a comprehensive Beginners Guide to TypeScript for FreeCodeCamp, but I wanted distil everything from the article into a concise, easy-to-revise-from cheat sheet. So that's what I did.

This cheat sheet explains the following fundamental TypeScript concepts, with code examples:

  • Setting up a project
  • Compiling TypeScript
  • Strict mode
  • Primitive types
  • Union types
  • Dynamic types
  • Literal types
  • Objects
  • Arrays
  • Tuples
  • Functions
  • Type aliases
  • Interfaces
  • The DOM and type casting
  • Generics
  • Enums
  • Narrowing

TypeScript Cheat Sheet PDF

One page PDF to make it easy to copy and paste in commands.

Download the free TypeScript Cheat Sheet PDF here.

Cheat sheets are available in Dark Mode and Light Mode:

TypeScript cheat sheet PDF dark

TypeScript cheat sheet PDF light

TypeScript Cheat Sheet Poster

Order a physical A3 poster for your office wall - so you can quickly look up commands, and keep them at the top of your head.

It comes in thick durable paper, and a matte, light-absorbing finish.

Order a TypeScript cheat sheet poster here

Here is everything included in the cheat sheet:

Setup

Install TS globally on your machine



$ npm i -g typescript


Enter fullscreen mode Exit fullscreen mode

Check version



$ tsc -v


Enter fullscreen mode Exit fullscreen mode

Create the tsconfig.json file



$ tsc --init


Enter fullscreen mode Exit fullscreen mode

Set the root (to compile TS files from) and output (for the compiled JS files) directories in tsconfig.json



"rootDir": "./src",
"outDir": "./public",


Enter fullscreen mode Exit fullscreen mode

Compiling

Compile a specified TS file into a JS file of the same name, into the same directory (i.e. index.ts to index.js)



$ tsc index.ts


Enter fullscreen mode Exit fullscreen mode

Tell tsc to compile specified file whenever a change is saved by adding the watch flag (-w)



$ tsc index.ts -w


Enter fullscreen mode Exit fullscreen mode

Compile specified file into specified output file



$ tsc index.ts --outfile out/script.js


Enter fullscreen mode Exit fullscreen mode

If no file is specified, tsc will compile all TS files in the "rootDir" and output in the "outDir". Add -w to watch for changes.



$ tsc -w


Enter fullscreen mode Exit fullscreen mode

Strict Mode

In tsconfig.json, it is recommended to set strict to true. One helpful feature of strict mode is No Implicit Any:



// Error: Parameter 'a' implicitly has an 'any' type
function logName(a) {
  console.log(a.name)
}


Enter fullscreen mode Exit fullscreen mode

Primitive Types

There are 7 primitive types in JS:

  • string
  • number
  • bigInt
  • boolean
  • undefined
  • null
  • symbol

Explicit type annotation



let firstname: string = "Danny"


Enter fullscreen mode Exit fullscreen mode

If we assign a value (as above), we don't need to state the type - TS will infer it ("implicit type annotation")



let firstname = "Danny"


Enter fullscreen mode Exit fullscreen mode

Union Types

A variable that can be assigned more than one type



let age: number | string
age = 26
age = "26"


Enter fullscreen mode Exit fullscreen mode

Dynamic Types

The any type basically reverts TS back to JS



let age: any = 100
age = true


Enter fullscreen mode Exit fullscreen mode

Literal Types

We can refer to specific strings & numbers in type positions



let direction: "UP" | "DOWN"
direction = "UP"


Enter fullscreen mode Exit fullscreen mode

Objects

Objects in TS must have all the correct properties & value types



let person: {
  name: string
  isProgrammer: boolean
}

person = {
  name: "Danny",
  isProgrammer: true,
}

person.age = 26 // Error - no age prop on person object

person.isProgrammer = "yes" // Error - should be boolean


Enter fullscreen mode Exit fullscreen mode

Arrays

We can define what kind of data an array can contain



let ids: number[] = []
ids.push(1)
ids.push("2") // Error


Enter fullscreen mode Exit fullscreen mode

Use a union type for arrays with multiple types



let options: (string | number)[]
options = [10, "UP"]


Enter fullscreen mode Exit fullscreen mode

If a value is assigned, TS will infer the types in the array



let person = ["Delia", 48]
person[0] = true // Error - only strings or numbers allowed


Enter fullscreen mode Exit fullscreen mode

Tuples

A tuple is a special type of array with fixed size & known data types at each index. They're stricter than regular arrays.



let options: [string, number]
options = ["UP", 10]


Enter fullscreen mode Exit fullscreen mode

Functions

We can define the types of the arguments, and the return type. Below, : string could be omitted because TS would infer the return type.



function circle(diam: number): string {
  return "Circumf = " + Math.PI * diam
}


Enter fullscreen mode Exit fullscreen mode

The same function as an ES6 arrow



const circle = (diam: number): string => "Circumf = " + Math.PI * diam


Enter fullscreen mode Exit fullscreen mode

If we want to declare a function, but not define it, use a function signature



let sayHi: (name: string) => void
sayHi = (name: string) => console.log("Hi " + name)
sayHi("Danny") // Hi Danny


Enter fullscreen mode Exit fullscreen mode

Type Aliases

Allow you to create a new name for an existing type. They can help to reduce code duplication.
They're similar to interfaces, but can also describe primitive types.



type StringOrNum = string | number
let id: StringOrNum = 24


Enter fullscreen mode Exit fullscreen mode

Interfaces

Interfaces are used to describe objects. Interfaces can always be reopened & extended, unlike Type Aliases. Notice that name is readonly



interface Person {
  name: string
  isProgrammer: boolean
}

let p1: Person = {
  name: "Delia",
  isProgrammer: false,
}

p1.name = "Del" // Error - read only


Enter fullscreen mode Exit fullscreen mode

Two ways to describe a function in an interface



interface Speech {
  sayHi(name: string): string
  sayBye: (name: string) => string
}

let speech: Speech = {
  sayHi: function (name: string) {
    return "Hi " + name
  },
  sayBye: (name: string) => "Bye " + name,
}


Enter fullscreen mode Exit fullscreen mode

Extending an interface



interface Animal {
  name: string
}

interface Dog extends Animal {
  breed: string
}


Enter fullscreen mode Exit fullscreen mode

The DOM & Type Casting

TS doesn't have access to the DOM, so use the non-null operator (!) to tell TS the expression isn't null or undefined



const link = document.querySelector("a")!


Enter fullscreen mode Exit fullscreen mode

If an element is selected by id or class, we need to tell TS what type of element it is via Type Casting



const form = document.getElementById("signupform") as HTMLFormElement


Enter fullscreen mode Exit fullscreen mode

Generics

Generics allow for type safety in components where the arguments & return types are unkown ahead of time



interface HasLength {
  length: number
}

// logLength accepts all types with a length property
const logLength = <T extends HasLength>(a: T) => {
  console.log(a.length)
}

// TS "captures" the type implicitly
logLength("Hello") // 5

// Can also explicitly pass the type to T
logLength<number[]>([1, 2, 3]) // 3


Enter fullscreen mode Exit fullscreen mode

Declare a type, T, which can change in your interface



interface Dog<T> {
breed: string
treats: T
}

// We have to pass in a type argument
let labrador: Dog<string> = {
breed: "labrador",
treats: "chew sticks, tripe",
}

let scottieDog: Dog<string[]> = {
breed: "scottish terrier",
treats: ["turkey", "haggis"],
}

Enter fullscreen mode Exit fullscreen mode




Enums

A set of related values, as a set of descriptive constants



enum ResourceType {
BOOK,
FILE,
FILM,
}
ResourceType.BOOK // 0
ResourceType.FILE // 1

Enter fullscreen mode Exit fullscreen mode




Narrowing

Occurs when a variable moves from a less precise type to a more precise type



let age = getUserAge()
age // string | number
if (typeof age === "string") {
age // string
}

Enter fullscreen mode Exit fullscreen mode




Thanks for reading

Hope this cheat sheet is useful!

Again, feel free to download the one-page PDF or order a poster:

One-page TypeScript cheat sheet PDF

Order a physical poster

For more from me, you can follow me on Twitter, or subscribe to my YouTube channel.

Cheers!

Top comments (3)

Collapse
 
mfaisalkhatri profile image
Mohammad Faisal Khatri

Thank you for this post!

Collapse
 
doabledanny profile image
Danny Adams

Glad it's helpful!

Collapse
 
shahzad6077 profile image
Muhammad Shahzad Ali

Great article @doabledanny πŸ˜€