TypeScript Cheat Sheet
Basics 👇
Advanced 👇
Type Inference See the official TypeScript documentation page
Without explicitly typing your variables, TypeScript is hable to infer types.
const ide = 'VSCode'; // It's "VSCode"
let browser = 'Brave'; // It's string
if (browser === 'Brave') {/* here */} // It's "Brave"
const theme = { name: 'Material' } // theme.name is string
Basic Types See the official TypeScript documentation page
boolean, string, number, number[], [string, number],
unknown, any, void, null, undefined, never
Assertions See the official TypeScript documentation page
let layout: unknown = 'qwertz'; // layout is unknown
let length: number = (layout as string).length; // layout is string
Custom Types See the official TypeScript documentation page
type Person = {
fullname: string;
};
or
interface Person {
fullname: string;
};
Here is a good article about choosing type
or interface
type Person = {
name: string; // mandatory
age?: number; // optional
prefer: 'cat' | 'dog'; // narrower
readonly birthdate: string; // read only
getName(): string; // function returns
}
Functions See the official TypeScript documentation page
const add = (x: number, y: number): number => x + y;
or
type Add = (base: number, increment: number) => number;
const add: Add = (x, y) => x + y;
Rest parameters
const joinList = (...items: string[]) => items.join(' ');
Async
const fetchItems = (query: string): <Promise<string[]>> => {
return fetch(`/items?q=${query});
};
This See the official TypeScript documentation page
function printValue(this: HTMLElement): void {
console.log(this.target.value);
}
Export/Import types
export type Cat = { name: string };
import type { Cat } from './my-types';
React simple pattern
import React, { useState } from 'react';
type Props = {
open: boolean;
onOpen(open: boolean): void;
}
const Accordion = ({ open, onOpen }: Props): JSX.Element => {
const [active, setActive] = useState<number | null>(null);
return (/* ... */);
};
export default Accordion;
Unions and Intersection Types See the official TypeScript documentation page
type Artwork = { title: string }
Intersection
type Movie = Artwork & { duration: number; kind: 'movie' }
type Photograph = Artwork & { iso: number; kind: 'photograph' }
Union
type PortfolioItem = Movie | Photograph;
Dynamic Union
type ArtKind = PortfolioItem['kind']; // 'movie' | 'photograph'
Mapped Types See the official TypeScript documentation page
type GroupedItem = {
[Kind in ArtKind]: PortfolioItem[];
};
// Is equal to
type GroupedItem = {
movie: PortfolioItem[];
photograph: PortfolioItem[];
};
keyof
type MovieProperties = keyof Movie; // 'title' | 'duration' | 'kind'
Generics See the official TypeScript documentation page
Generics are like functions, it takes arguments that can be used in the type definition.
type PortfolioItem<Kind extends Kinds> = {
title: string;
kind: Kind;
};
const myArtWork: PortfolioItem<'movie'> = {/*...*/};
const identity = <T>(arg: T): T => arg; // not very usefull ^^'
// Takes a type T, arg is a type of T and returns a type T
identity('Hello'); // OK
identity(42); // OK
identity(true); // OK
Utility Types See the official TypeScript documentation page
// Partial type
const changeTitle = (movie: Movie, newTitle: Partial<Movie>) => {
return { ...movie, title: newTitle };
};
// Readonly type
const sw: Readonly<Movie> = { title: 'Star Wars', duration: 121 };
sw.title = 'Star Trek'; // Error!
// Record, like an object description <key, type>
const library: Record<string, Movie> = {
starWars: { title: 'Star Wars', duration: 121 }
};
// Pick certains attributes
const titleOnly: Pick<Movie, 'title'> = { title: 'Her' };
// Omit certains attributes
const noTitle: Omit<Movie, 'title'> = { duration: 90 };
Conditional Types See the official TypeScript documentation page
type Library<Item extends PortfolioItem> =
Item extends Movie ? Movie[] :
Item extends Photograph ? Photograph[] : never;
type SelectItem<Item, Kin> =
Item extends { kind: Kin } ? Item : never;
// With infer keyword
type GetReturnType = T extends (...args: never[]) =>
infer U ? U : never;