-
-
Notifications
You must be signed in to change notification settings - Fork 164
Description
Is your feature request related to a problem? Please describe.
We work on a typescript project and I often find myself needing to declare schema with new SimpleSchema(objectSchema)
and also declaring the type in typescript
Example:
// A silly example
const chairSchema = new SimpleSchema({
constructionDate: {
type: Date,
autoValue() {
return new Date();
},
},
legsCount: Number,
});
type ChairToInsert = {
/**
* Optional since there is an autovalue
*/
constructionDate?: Date;
legsCount: number;
};
type ChairInDatabase = {
_id: string;
/**
* When we fetch for the document in database, the autovalue is set so we get the value
*/
constructionDate: Date;
legsCount: number;
};
I found that it's quite redundant since all informations are contained in the schema and it can be painful to maintain in a large scale project.
Describe the solution you'd like
I think it would be great to have a generic schema type
class SimpleSchema<TSchema extends SimpleSchemaDefinition> {
constructor(schema: TSchema, options?: SimpleSchemaOptions){
// Work here
}
}
And also some type helpers that parses the TSchema
type to provide some useful types such as the type inserted and the type received
(not completed) Example:
type OutTypeFromObj<T> = {
[k in keyof T]: OutTypeFromAny<T[k]>;
};
/** TODO */
type OutTypeFromAny<T> = any;
/**
* Provides the output type from the database
*/
type OutTypeFromSchema<T> = T extends SimpleSchema<infer U> ? OutTypeFromObj<U> : never;
It would be a nice to have:
- Input type from schema
- Output type
That takes into account the defaultValue
, autoValue
, and 'optional' fields in the schema
Describe alternatives you've considered
Some packages provides such flexibility such as zod
, that provides some typing helpers type MyObject = z.infer<typeof someZodObj>