Hacker News new | past | comments | ask | show | jobs | submit login

What's the type definition of the map out of interest?



  const Json = union(enum) {
      null,
      number: f64,
      bool: bool,
      string: []const u8,
      array: []const Json,
      object: HashMap([]const u8, Json),
  };

Usually it's a tagged union of the base JSON types which can easily be consumed by most statically typed languages or a variant of it.

EDIT: added "tagged"



In TS JSON is usually Record<string, unknown>.


Well unknown is not a type (by definition), so you have just stepped outside of a type system, which is very common in TS if I understand.


Unknown is a top type in the TS type system. It serves the very important role of "here you need to apply some pattern matching and validation" and then you can make sure that you can continue working in a type safe environment. TS has a lot of facilities that help you with this (from the usual narrowing things, typeof and instanceof guards, control flow analysis, and at the end of the list there are the big guns like this thing called type predicates which basically allows you to wrap these checks and "casts" in nice reusable functions).

There are also recursive types that help you model JSON, but knowing that it's an arbitrary deep nested map/list of maps/lists and number and bool and string mixed like a Bloody Mary cocktail doesn't really help :)

With NestJS it's very easy to add decorators/annotations to fields of a class, and the framework handles validation (throws HTTP 422 with nice descriptions of what failed) and then in your controller you can again work in a type safe environment.

https://www.typescriptlang.org/docs/handbook/release-notes/t...

https://www.typescriptlang.org/docs/handbook/2/narrowing.htm...


Json = Map<string, Json>




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: