[英]Gel all model attributes of a class in TypeScript
我有以下 TypeScript 类:
export class City {
name: string;
fullName: string;
country: string;
countryCode: string;
center: GeoPoint;
}
我需要一种在运行时获取所有模型属性的方法。 例如:
static init(obj): City {
let city = new City();
for (var i in obj) {
if (i == "exists in City model") {
city[i] = obj[i];
}
}
}
在 TypeScript 中有一种简单的方法可以做到这一点吗? 我不想被要求维护所有模型属性名称的数组来检查这一点。
如果您在TypeScript Playground上检查 TypeScript 编译器生成的输出,它不会设置任何没有默认值的类属性。 所以一种可能的方法是用null
初始化它们:
export class City {
name: string = null;
fullName: string = null;
country: string = null;
countryCode: string = null;
center: string = null;
...
}
然后检查对象属性是否存在于对象上: typeof
。 您更新的代码:
export class City {
name: string = null;
fullName: string = null;
country: string = null;
countryCode: string = null;
center: string = null;
static init(obj): City {
let city = new City();
for (var i in obj) {
if (typeof(obj[i]) !== 'undefined') {
city[i] = obj[i];
}
}
return city
}
}
var c = City.init({
name: 'aaa',
country: 'bbb',
});
console.log(c);
编译并使用node
运行时打印输出:
City {
name: 'aaa',
fullName: null,
country: 'bbb',
countryCode: null,
center: null
}
您可以试用 TypeScript 编译器的增强版本,它允许您在运行时检索类/接口元数据(字段、方法、泛型类型等)。 例如,您可以编写:
export class City {
name: string = null;
fullName: string = null;
country: string = null;
countryCode: string = null;
center: string = null;
}
function printMembers(clazz: Class) {
let fields = clazz.members.filter(m => m.type.kind !== 'function'); //exclude methods.
for(let field of fields) {
let typeName = field.type.kind;
if(typeName === 'class' || typeName === 'interface') {
typeName = (<Class | Interface>field.type).name;
}
console.log(`Field ${field.name} of ${clazz.name} has type: ${typeName}`);
}
}
printMembers(City.getClass());
这是输出:
$ node main.js
Field name of City has type: string
Field fullName of City has type: string
Field country of City has type: string
Field countryCode of City has type: string
Field center of City has type: string
然后,您可以在for
循环中使用City
元数据来检查特定实例上是否存在值。
您可以在此处找到有关我的项目的所有详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.