4 ms·
What's the type definition of the map out of interest?
by tus666 5y ago
What's the type definition of the map out of interest?
- pas 5y agoIn TS JSON is usually Record<string, unknown>.
- tus666 5y agoWell 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.
- pas 5y agoUnknown 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/typescript-3-0.html#new-unknown-top-type https://www.typescriptlang.org/docs/handbook/release-notes/t... https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates https://www.typescriptlang.org/docs/handbook/2/narrowing.htm...
- staticassertion 5y agoJson = Map<string, Json>
- nyberg 5y agoconst 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"
- steveklabnik 5y agoIn Rust: https://docs.serde.rs/serde_json/value/enum.Value.html https://docs.serde.rs/serde_json/value/enum.Value.html