Hacker News new | ask | show | jobs
by smichel17 2161 days ago
Is there any language that does both? I've really enjoyed js/ts's structural typing for prototyping, but there are certain places I miss nominal typing, particularly with input validation (and other "primitive type, plus restrictions") scenarios.

For example, an integer that's used to index into an array, so it must be positive. Or a string that's a valid street address. You can maintain that info by packing it into a unique structure (ie, wrap in an object, using a unique key), but that's awkward to access. Or you can always pass around the parent object (eg, House), which has a unique structure, but then you're introducing unnecessarily tight coupling which is a disaster to maintain.

3 comments

If I understand correctly you want "new types" in typescript, which can be done either via a library or by hand rolling it:

- https://github.com/gcanti/newtype-ts

- https://github.com/Microsoft/TypeScript/issues/4895#issuecom...

but it isn't as nice as say Python's `typing.NewType` or Haskell's `newtype`

I believe classes are nominally typed in TypeScript. Otherwise, OCaml has row polymorphic records, polymorphic variants, and a structurally typed object system, in addition to a powerful nominal type system with ADTs and higher-order modules and such.
There are a couple of attempts in that direction with TypeScript[1,2]. A bit more work than if there was direct language support, but I've used "branded types" to distinguish between UserIds and ProductIds, between different types of currency, and between different unit systems.

1: https://spin.atomicobject.com/2018/01/15/typescript-flexible...

2: https://basarat.gitbook.io/typescript/main-1/nominaltyping