Skip to Content
Learning TypeScript 2.x - Second Edition
book

Learning TypeScript 2.x - Second Edition

by Remo H. Jansen
April 2018
Beginner content levelBeginner
536 pages
13h 21m
English
Packt Publishing
Content preview from Learning TypeScript 2.x - Second Edition

Functor

A Functor is an object that holds a value and implements a method named map. The following code snippet declares a class named Container. This class can be considered a Functor:

class Container<T> { 
    private _value: T; 
    public constructor(val: T) { 
        this._value = val; 
    } 
    public map<TMap>(fn: (val: T) => TMap) { 
        return new Container<TMap>(fn(this._value)); 
    } 
} 

We can use the container as follows:

let double = (x: number) => x + x;
let container = new Container(3); 
let container2 = container.map(double); 
console.log(container2); // { _value: 6 } 

At this point, it might feel like a Functor is not very useful because we have implemented the most basic version possible. The next two sections implement two functors known as Maybe and Either ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering TypeScript - Fourth Edition

Mastering TypeScript - Fourth Edition

Nathan Rozentals
Learning TypeScript

Learning TypeScript

Josh Goldberg
TypeScript for Beginners

TypeScript for Beginners

Bharath Thippireddy

Publisher Resources

ISBN: 9781788391474Supplemental Content