Typescript Cookbook

Function Declarations:

Example 1: Arguments with type:

function greet(person: string, date: Date) {console.log(`Hello ${person}, today is ${date.toDateString()}!`);}

Example 2: Return type:

function randomNumber(): number {return 26;}
// says that randomNumber will return a number

Example 3: Argument with an Object type:

function printCoord(pt: { x: number; y: number }) {console.log("The coordinate's x value is " + pt.x + pt.y);}
/* says that pt is an argument with type object having properties x and y */

Example 4: Argument with an Object type with Refactor:

type Point = {x: number;y: number;};// Exactly the same as the earlier examplefunction printCoord(pt: Point) {console.log("The coordinate's x value is " + pt.x + pt.y);}
/* says that pt is an argument with type Point

Example 5: Argument can be a string or number or something else

function printId(id: number | string) {if (typeof id === "string") {// In this branch, id is of type 'string'console.log(id.toUpperCase());} else {// Here, id is of type 'number'console.log(id);}}

Example 6: Argument that can have some set of values only

function printText(s: string, alignment: "left" | "right" | "center") {}printText("Hello, world", "left");interface Options {width: number;}function configure(x: Options | "auto") {// ...}configure({ width: 100 });configure("auto");

Example 7: Generic Function Declaration

function identity<Type>(arg: Type): Type {return arg;}identify(4);


Example 1: Only attributes:

interface IPerson {
name: string;
age: number;

Example 2: Attributes and Functions:

interface IEmployee {
empCode: number;
empName: string;
getSalary: (number) => number;
// arrow function that returns a number
getManagerName(number): string;
// function that returns a string and takes number as argument.

Example 3: Generic Interface with Attributes and Functions:

interface IArray<Type> {length: number;pop(): Type | undefined; // function can either return an element of // data type Type or undefinedpush(...items: Type[]): number;
// function that returns a number may be the current index value.

Example 4: Optional properties in Interfaces

interface IRectangle {length: number;breadth: number;area?: number;}

Example 5: Inheriting and Extending Interfaces

interface IHuman {type: string;origin: string;country?: string;}interface IMan extends IHuman {address: string;}

Handling Types which typescript can’t infer

const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");


Example 1:Numeric enums:

enum Direction {Up = 1,Down,Left,Right,}
enum Direction {Up,Down,Left,Right,}

Example 2:String enums

enum Direction {Up = "UP",Down = "DOWN",Left = "LEFT",Right = "RIGHT",}

Modules , Import, Exports

// @filename: maths.tsexport var pi = 3.14;export let squareTwo = 1.41;export const phi = 1.61;export class RandomNumberGenerator {}export function absolute(num: number) {if (num < 0) return num * -1;return num;}
import { pi, phi, absolute } from "./maths.js";console.log(pi);const absPhi = absolute(phi);
import { pi as π } from "./maths.js";console.log(π);




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Vector rendering of SVG content with PixiJS

What is Node.js

How to Create a Linked List in JavaScript

React Native: Building a Minimalist Weather App using Expo XDE

Functions to the Rescue

React Native Coding Standards and Best Practices

Working with shared UI components

Coding on the smartphone?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Till Engineering

Till Engineering

More from Medium

What are my global npm packages?

TypeScript’s Template Literal Types advanced usage

Complete Dive Into TypeScript: Part 1

TypeScript 4  — Introduction