Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell's newtypes in Typescript?

In Haskell we can declare newtypes that allow us to hide access to the underlying data types. This allows us to create safer APIs in modules by not exposing things like the underlying array (making it impossible for the user of the library to get something out of bounds).

Is there something similar to newtypes in Typescript?

like image 728
Marc Avatar asked Mar 14 '19 04:03

Marc


2 Answers

FWIW a class with a single private field is more or less the same thing, so it’s not like a keyword is strictly needed for this.

Also note that the point of newtype in Haskell isn’t really encapsulation, although you can use it that way - it’s to enable having different types for the same structural representation, to prevent accidental misuse and to allow type based ad hoc polymorphism via type classes. Haskell’s data works pretty much the same way, other than implementation details the difference between newtype A = A X and data A = A X is more philosophical than technical.

like image 124
Cubic Avatar answered Oct 01 '22 18:10

Cubic


As a follow up to this, there is another way you can introduce something similar to newtypes.

You can do the following:

type Seed = number & {readonly Seed: unique symbol}

const createSeed = randomNumberBetween0And1() as Seed

const doSomethingWithSeed = (s: Seed) => {...}

doSomethingWithSeed(1) // will complain
doSomethingWithSeed(createSeed()) // Will not complain
like image 27
Marc Avatar answered Oct 01 '22 16:10

Marc