inherit classes in typescript by omitting properties

Viewed 123

I am trying to inherit a class in TypeScript ignoring some properties of the parent class.

This is my code:

import {IsInt, IsUUID, MaxLength, Min, MinLength, validate} from 'class-validator';

class Person {
    @IsUUID()
    id: string;

    @MinLength(2)
    @MaxLength(5)
    name: string;
}

class OtherPerson extends Person {
    @Min(18)
    @IsInt()
    age: number;
}

const otherPerson = new OtherPerson();

otherPerson.age = 20;
otherPerson.name = 'kkkk';

validate(otherPerson).then(console.log).catch(console.error);

With this code the validate method returns error with id param.

and this is the code that i want:

import {IsInt, IsUUID, MaxLength, Min, MinLength, validate} from 'class-validator';

class Person {
    @IsUUID()
    id: string;

    @MinLength(2)
    @MaxLength(5)
    name: string;
}

class OtherPerson extends Omit(Person, ['id']) { // This is that i want
    @Min(18)
    @IsInt()
    age: number;
}

const otherPerson = new OtherPerson();

otherPerson.age = 20;
otherPerson.name = 'kkkk';

validate(otherPerson).then(console.log).catch(console.error);

With this code the validate method shouldn't returns error with id param.

Any ideas to achieve this?

thank you!

PD: My idea is based on these functionalities provided by NestJS but I can't understand how they make it work: https://docs.nestjs.com/graphql/mapped-types

0 Answers
Related