简体   繁体   中英

Get class (interface) properties in Angular 5 / TypeScript without assigning a default value

Let's pretend that I have an interface A, that I am declaring as a class by following the Angular style guide. This class has many properties, and I want to fetch them names without having to assign any value to them. How can I achieve this ?

Class A:

export class A {
  property1: string;
  property2: string;
  ...
  property30: string;
}

I tried with instantiating a new object from this class and calling Object.keys and Object.getOwnPropertyNames but this two methods return an empty array because they are ignoring undefined value properties. Is there any way to bypass this behaviour ? Or am I breaking the JavaScript/TypeScript pattern ? :D

The way properties declarations work is that they are just a hint to the compiler that that property may exist at run-time. In JavaScript you don't need to declare fields, so until the field is assigned it will not exist on the object. If you initialize the field even just with null or undefined the field will appear on the object. This is the simplest way to achieve what you want.

The other way would be to use a decorator on every field. This would be more explicit but not shorter and not necessarily less error prone

Make sure your compiler supports class first. And then you have to do either interface or class. Ex. if it's a class, you need to do

class A {
    title = ''
}
var a = new A();
console.log(a);

declare title as a string, title: String = '' . Your writing is more for the interface. Here's the output,

Object {
    title: ""
}

Yeah, I understand your question better now, without assignment, it doesn't set the properties.

interface B {
    title: String;
}
class A implements B {
    title = '';
}
var a = new A();
console.log(a);

If that's the case, a simple solution is to give some default value of that property. Or going through a list to manually initialize all of them based by their type.

class A {
    keys = {
        title: 'String'
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM