在Angular 5/TypeScript中获取类(接口)属性,而不分配默认值 [英] Get class (interface) properties in Angular 5 / TypeScript without assigning a default value

查看:239
本文介绍了在Angular 5/TypeScript中获取类(接口)属性,而不分配默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假装我有一个接口A,我将按照Angular样式指南将其声明为一个类.此类具有许多属性,我想获取它们的名称而不必给它们分配任何值.我该如何实现?

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 ?

A类:

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

我尝试从此类实例化一个新对象并调用Object.keysObject.getOwnPropertyNames,但是这两个方法返回一个空数组,因为它们忽略了未定义的值属性.有什么办法可以绕过这种行为?还是我打破了JavaScript/TypeScript模式? :D

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

推荐答案

属性声明的工作方式是它们只是向编译器暗示该属性可能在运行时存在.在JavaScript中,您无需声明字段,因此在分配该字段之前,该对象将不存在.如果仅使用nullundefined初始化字段,则该字段将出现在对象上.这是实现您想要的最简单的方法.

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

这篇关于在Angular 5/TypeScript中获取类(接口)属性,而不分配默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆