打字稿循环遍历类类型属性 [英] Typescript looping through class type properties
问题描述
如何在 TypeScript 中遍历类的属性?以下面的类为例:
How can one loop through the properties of a class in TypeScript? Take the following class for example:
export class Task implements Itask {
public Id: number = 0;
public Name: string;
public Description: string;
public Completed: boolean = false;
public TaskType: TaskType;
}
我想检索属性,因此:["Id", Name", "Description", "Completed", "TaskType"]
Im want to retrieve the properties, hence: ["Id", Name", "Description", "Completed", "TaskType"]
尝试过
GetTaskHeaders = () => {
const _self = this;
const tHead = $('<thead />').append('<tr />');
for (let i = 0; typeof TodoApp.Task.arguments; i++) {
const th = $('<th />');
th.append(TodoApp.Task.arguments[i]);
tHead.append(th);
}
console.log(tHead);
return tHead;
};
不幸的是没有成功,我知道使用TodoApp.Task.arguments"是不正确的.但是,有人可以告诉我正确的方法吗?
Unfortunately without success, i know using "TodoApp.Task.arguments" is incorrect. However, can someone show me the right way please?
推荐答案
让我们考虑所有未定义"属性,即所有在 typescript 类中定义的属性,如(我写的是未定义"而不是 undefined
原因在下面会很清楚)
Let's consider that all "not defined" properties i.e. all properties that are defined in the typescript class like (I wrote "not defined" and not undefined
for a reason that will be clear below)
class A {
prop1: string
prop2: number
}
不会被任何 Object.keys
或 this.hasOwnProperty(k)
枚举,因为 autogen javascript 不知道这些属性.当您创建打字稿类时,您只有一种选择,即将所有属性初始化为默认值,如
will not be enumerated by any of Object.keys
or this.hasOwnProperty(k)
since the autogen javascript has no knowledge of those properties.
You have only one option, when you create your typescript class, that is to initialize all properties to default values like
class A {
prop1: string
prop2: number
prop3: B
constructor() {
this.prop1="";
this.prop2=-1;
this.prop3=null;
}
}
此时你将从字典中获得A
实例的所有属性,就像在这个映射迭代中一样
At this point you will get all the properties of A
instance like in this mapping iteration from a dictionary
var a = new A();
for (var i in properties) {
if (a.hasOwnProperty(i)) {
a[i]=properties[i];
}
}
如果您不喜欢默认值解决方案,您仍然可以使用神奇的 undefined
javascript 关键字来执行此操作:
If you don't like the default values solution, you can still do this using the magic undefined
javascript keyword so that you do:
class A {
prop1: string = undefined
prop2: number = undefined
}
此时 javascript 副本将拥有模型中的所有属性,您将使用 Object.keys(this)
迭代它们或通过 this.hasOwnProperty
检查它们
At this point the javascript counterpart will have all properties in the model and you will iterate them with Object.keys(this)
or inspect them via the this.hasOwnProperty
这篇关于打字稿循环遍历类类型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!