Javascript 在TypeScript中对类的所有模型属性进行凝胶处理
我有以下TypeScript类:Javascript 在TypeScript中对类的所有模型属性进行凝胶处理,javascript,reflection,typescript,Javascript,Reflection,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
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编译器生成的输出,它不会设置任何没有默认值的类属性。因此,一种可能的方法是使用
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);
使用节点编译和运行时打印输出:
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());
然后,您可以在for
循环中使用City
元数据来检查特定实例上是否存在值
你可以找到关于我的项目的所有细节TypeScript没有提供任何额外的信息,所以你要用js的方式来做。
$ 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