Search code examples
javascripttypescripttypeorm

Get class properties having existing object in TypeScript


I would like to find out if it is possible to get all properties of a class having an object that is created as an instance of this class.

The thing is that I'm trying to create a generic admin page for any entity that it is bound to. I use TypeORM and I managed to fetch required entity repository from which I am able to get an instance of entity object(s).

Now, how can I get the class of this generic entity to iterate over its properties? I need it to create input fields on the view-side. This is not a problem when I process existing entities (at least when I have all the data filled in for them) but it is a bit of a challenge when trying to create a new entity, as the instance I get is a pristine empty object and trying to console.dir it returns something like City {}.

Here is some basic code on the subject:

public static build(req: Request, res: Response, entityRepository: Repository<any>, args: any) {
    // ...
    if (args.action === 'create') {
        const targetEntity: Function = <Function> entityRepository.target();
        let entity = entityRepository.create();

        // Now I need to get the class of this entity to 
        //pass it to the view that will display input fields accordingly
        console.dir(Object.getPrototypeOf(entity)); // Output: City {}

        // ...
    }
}

UPDATE

I would paraphrase my question.

I came across the fact that I can obtain the class of the object, but I do not get its properties if they are not defined. E.g.:

class Foo {
    bar: any;
}

Getting own properties on this class returns [].

But:

class Foo {
    bar: any = "";
}

This will return ['bar'].

So, how can I get CLASS property names instead of OBJECT property names even when their values are not defined? I'd prefer to avoid defining every single property on every entity with dummy value like '' and 0.


Solution

  • I'd prefer to avoid defining every single property on every entity with dummy value like '' and 0.

    Such dummy values actually help optimize the Machine code generated by JIT compilers in JavaScript runtimes.

    More importantly you can't get the key names as the generate JavaScript doesn't have introspection features to assist in this case.

    An alternative is to try instanceof but that only tells the type of the class ... not its properties.