Fp-ts: ADTs Guide

Created on 9 Oct 2020  路  2Comments  路  Source: gcanti/fp-ts

馃摉 Documentation

In the documentation there's a suggestion on how to implement ADTs with _TypeScript_:

interface Bar {
  readonly _tag: 'Bar'
  readonly value: string
}

interface Baz {
  readonly _tag: 'Baz'
  readonly value: boolean
}

// type
type Foo = Bar | Baz

// constructors
const Bar = (value: string): Foo => ({ _tag: 'Bar', value })

const Baz = (value: boolean): Foo => ({ _tag: 'Baz', value })

I wonder why can't we use classes instead? They come with a constructor for free:

class Bar {
  readonly _tag = 'Bar';
  constructor(readonly value: string) {}
}

class Baz {
  readonly _tag = 'Baz';
  constructor(readonly value: boolean) {}
}

// type
type Foo = Bar | Baz

What can go wrong and what are the limitations of this approach?

Most helpful comment

Class-based approached was abandoned in previous versions of fp-ts because of limitations of js/ts.

All 2 comments

Class-based approached was abandoned in previous versions of fp-ts because of limitations of js/ts.

@SRachamim I usually use classes as members of ADTs as you described and I am not aware of any limitation.

The class-based approach in reference above from which fp-ts migrated away refers to fluent APIs that are indeed very problematic.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mohsensaremi picture mohsensaremi  路  3Comments

bioball picture bioball  路  4Comments

maciejsikora picture maciejsikora  路  3Comments

FredericLatour picture FredericLatour  路  3Comments

amaurymartiny picture amaurymartiny  路  4Comments