I've been working on a server application that receives input data in the form of JavaScript objects. My main task is to validate whether these data meet certain requirements, such as:
- having all required fields specified by an interface
- ensuring that these fields are of specific types
- verifying that the object contains only the listed fields and nothing else
In my quest to achieve this goal, I have come across two libraries that have proved to be incredibly helpful:
These libraries are runtypes and io-ts
For instance, using runtypes, I am able to define runtime types like so:
const PropSchema = Record({
uid: String,
name: String,
timestamp: Number
});
Furthermore, I can create a static type based on PropSchema:
type PropSchemaInterface = Static<typeof PropSchema>;
From now on, I can utilize it as if it were an interface, and TypeScript will flag any invalid objects:
let props: PropSchemaInterface = {
uid: "31293-a7aa216982678",
name: 4,
timestamp: (new Date()).valueOf()
}
I can also check if an object satisfies PropSchema:
PropSchema.check(props); // returns true
However,
PropSchema.check({
uid: "12"
});
results in an error because the provided object lacks the 'name' and 'timestamp' properties. While this validation is helpful, what I truly need is a way to ensure that the input object contains only the fields defined in PropSchema, without any additional keys. Unfortunately, I haven't found a library that can handle this particular requirement.
Is there a method to validate objects according to my specifications? Runtypes has proven to be an invaluable tool for both runtime and compile-time validation using a single descriptor - PropSchema. However, I'm struggling with verifying invalid object members. IO-TS offers similar capabilities, but I have yet to explore its full potential.