我有以下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中有一种简单的方法吗?我不希望需要维护所有模型属性名称的数组来检查它。
答案 0 :(得分:1)
如果在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
}
答案 1 :(得分:0)
您可以尝试使用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
然后,您可以在City
循环中使用for
元数据来检查特定实例上是否存在值。
您可以找到有关我的项目here
的所有详细信息