You can achieve this using a library like class-transformer along with class-validator. First, you need to install these libraries:
npm install class-transformer class-validator
Next, create the TypeScript interface and class for your schema:
// exampleSchema.ts
import { IsString, IsNumber, validateOrReject } from 'class-validator';
export interface ExampleInterface {
name: string;
age: number;
}
export class ExampleClass implements ExampleInterface {
@IsString()
name: string;
@IsNumber()
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
static async fromJSON(json: string): Promise<ExampleClass> {
const parsedJson = JSON.parse(json);
const instance = new ExampleClass(parsedJson.name, parsedJson.age);
// Validate the instance against the schema
await validateOrReject(instance);
return instance;
}
}
Now you can use the fromJSON method to deserialize the JSON string and validate it against the schema:
// main.ts
import { ExampleClass } from './exampleSchema';
async function main() {
const jsonString = '{"name": "John Doe", "age": 30}';
try {
const exampleInstance = await ExampleClass.fromJSON(jsonString);
console.log('Deserialized and validated object:', exampleInstance);
} catch (error) {
console.error('JSON is not valid:', error);
}
}
main();
If the JSON string doesn't match the schema, an error will be thrown, and you can catch and handle it as needed.