Para este código, donde tengo una interfaz definida por el usuario y se guía la definición del esquema.
type SchemaDefinition<T> = { [K in keyof T]: { type: { new(): unknown } // required?: boolean } } class Schema<T> { constructor(public schema: SchemaDefinition<T>) {} validate(obj: T): boolean { for (const prop of Object.keys(this.schema) as (keyof T)[]) { if (!(obj[prop] instanceof this.schema[prop].type)) return false if (this.schema[prop].required && obj[prop] == null) return false } return true } } interface IUser { name: string; email: string; }Hay dos esquemas aquí. 1. para el contenedor específico del lenguaje de programación que es la interfaz IUser 2. el que quiero enviar al backend que está compuesto por un objeto Schema algo así como
new Schema<IUser>('users', { name: {type: Number, required: true}, email: {type: String, required: true}, }); ahora estoy tratando de serializar este objeto Schema en una cadena usando JSON.stringify() pero se omite el type , ¿cómo puedo serializarlo o cómo puedo traducir este IUser al esquema JSON de la mejor manera en TS?
Editar:
Pude recuperar el nombre del tipo haciendo algo como esto
const schemaRepresentation = {}; schemaRepresentation['title'] = this._name; schemaRepresentation['additionalProperties'] = false; schemaRepresentation['additionalProperties'] = false; const properties = {}; for (const schemaKey in this.schema) { properties[schemaKey.toString()] = this.schema[schemaKey].datatype.name; } schemaRepresentation['properties'] = propertiessi hay un campo de matriz en la interfaz, ¿cómo obtengo el tipo de matriz?
Solo necesita usar valores que sean serializables para JSON porque String y Number son funciones y, por lo tanto, no son serializables.
Por ejemplo, tal vez quiera probar el tipo de typeof obj[prop] para una cadena en particular.
type AllowedTypeNames = 'string' | 'number' | 'boolean' type SchemaDefinition<T> = { [K in keyof T]: { type: AllowedTypeNames required?: boolean } } Y validate ahora se vería así:
validate(obj: T): boolean { for (const prop of Object.keys(this.schema) as (keyof T)[]) { if (typeof obj[prop] !== this.schema[prop].type) return false // ^ check if the typeof the obj[prop] matches the schema. if (this.schema[prop].required && obj[prop] == null) return false // ^ check if the typeof the obj[prop] is required and present. } return true }Que serializa bien:
const userSchema = new Schema<IUser>({ name: { type: 'string', required: true }, email: { type: 'string', required: true }, }); console.log(JSON.stringify(userSchema.schema)) // {"name":{"type":"string","required":true},"email":{"type":"string","required":true}}