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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With