Search code examples
typescriptclasspropertieshasownproperty

How to I get all properties name of class and use them as a static variable in TypeScript?


In my project using TypeScript, I have a class like

class Car {
    model: string;
    year: number;
    price: string;

    constructor(model: string, year: number, price: string) {
        this.model = model;
        this.number = number;
        this.price = price;
    }
}

I have to read data from a json file. And the first thing, I need to check data from file has the same property of Car class. I don't want to hash code fileData.hasOwnProperty('model'). My idea is similar to fileData.hasOwnProperty(Car.model). I want to make class properties as static recommend properties of Car class.

I would like to be able to reference any property in a class, such as Car.model, Car.year, or Car.price, ... in a way that returns the property name or similar information.

Do you have any idea for that?

Thank you so much

I tried like the following. But I don't think it's a good idea. Because in the future if I add more 5 properties, I also have to add 5 corresponding methods. And I don't want to add more methods in this case.

class Car {
    model: string;
    year: number;
    price: string;

    constructor(model: string, year: number, price: string) {
        this.model = model;
        this.number = number;
        this.price = price;
    }

    static model() {
        return 'model';
    }

    static year() {
        return 'year';
    }

    static price() {
        return 'price';
    }
}

I also try like the following. But It didn't recommend property name when I want to call Car.properties.model

class Car {
    model: string;
    year: number;
    price: string;

    constructor(model: string, year: number, price: string) {
        this.model = model;
        this.number = number;
        this.price = price;
    }

    static properties() {
        return Object.getOwnPropertyNames(Car).map((property) => { property });
    }
}

Solution

  • Thanks everyone for your answer! After careful consideration, I've decided to use class-validator and class-transformer for validation. This allows me to validate required properties and their types without manually specifying each property's name and type. The example here demonstrates how class-validator works, but in my project, I’ll use class-transformer to convert data with plainToInstance before running validations. ` import { IsNotEmpty, IsString, IsInt } from "class-validator"; import "reflect-metadata";

    export class Car {
        @IsNotEmpty()
        @IsString()
        model: string;
    
        @IsInt()
        year: number;
    
        @IsString()
        price: string;
    }
    

    Call validate

    validate(car).then(errors => {
      if (errors.length > 0) {
        throw new Error("Errors: " + errors.join("\n"));
      }
    });