Hacker News new | ask | show | jobs
by hamstercat 2161 days ago
I come from a TypeScript background, so I can compare it to that. The biggest difference to me was the soundness of the type system, where you're ensured (from a runtime perspective) that objects are correctly typed.

This cuts both way: it was great not having to think about typings all the time around input/output, but it was also cumbersome when implementing the internal implementation. I'm a bit biased because I've come to think in term of structural typing much more. Typing in Dart reminded me more of my time with C#.

Null safety was a huge missing piece though, glad to see it being added.

1 comments

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.

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