#Type error custom messages or class validation on every typed object creation?

10 messages · Page 1 of 1 (latest)

grand saffron
#

I have a type that's being "layered" from data in several json files.

I am reading a json, parsing it into my type (an object with optional fields, some fields have literal types), then layering the new object over the old one with a destruct-restruct ({ ...previous, ...next }) in a reducer mapper function for this type. Repeats for every specified file.

If the value doesn't match the type, I want to print a human-readable error like Source: ${source}. Issue: Wrong value in ${parameter}, should be ${expectedType} at runtime.

What would be a "better" pattern here? Should I maybe transition from "type & namespace" to using classes and class constructor definition?

bitter stream
#

If the value doesn't match the type, I want to print a human-readable error like Source: ${source}. Issue: Wrong value in ${parameter}, should be ${expectedType}.
you mean at runtime, right?
if so, there are plenty of libraries to help you defined schema and ensure objects match those schema
and let you provide custom error messages

#

the most well-known library for that is probably zod
other well-known libs include yup, joi, arktype, or typebox

#

Should I maybe transition from "type & namespace" to using classes and class constructor definition?
not really
in terms of types, there is little to no difference between an a class, a type, and an interface
use classes if it makes sense for you to have those at runtime and if you are actually using the benefits they provide (methods, inheritance, etc.)
otherwise raw types might be just as good, and don't need to be instantiated

#

one thing to keep in mind is that with most of the libraries mentioned above, the types are derived from the schema
you first create a schema (runtime object), and use some type magic to infer the type from that schema, and can reuse that type throughout your project

grand saffron
bitter stream
grand saffron
wild olive
#

you can do stuff like that with compiler plugins or other build-time code generation tooling, but not just with vanilla typescript

#

see typia for example