Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
Esquema Json de la interfaz: a la serialización le faltan algunos campos

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'] = properties

si hay un campo de matriz en la interfaz, ¿cómo obtengo el tipo de matriz?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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}}

ver parque infantil

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!