简体   繁体   English

在Angular 5 / TypeScript中获取类(接口)属性,而不分配默认值

[英]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. 假设我有一个接口A,并按照Angular样式指南声明为类。 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: 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. 我尝试从此类实例化一个新对象并调用Object.keysObject.getOwnPropertyNames但是这两个方法返回一个空数组,因为它们忽略了未定义的值属性。 Is there any way to bypass this behaviour ? 有什么办法可以绕过这种行为? Or am I breaking the JavaScript/TypeScript pattern ? 还是我打破了JavaScript / TypeScript模式? :D :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. 在JavaScript中,您无需声明字段,因此在分配该字段之前,该对象将不存在。 If you initialize the field even just with null or undefined the field will appear on the object. 如果仅使用nullundefined初始化字段,则该字段将出现在对象上。 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 = '' . 声明title为字符串, 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'
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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