javascript - 获取 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 中有简单的方法来做到这一点吗?我不想被要求维护一个包含所有模型属性名称的数组来检查这个。
答案#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
}
答案#2
您可以尝试一个增强版的 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 元数据来检查特定实例上值的存在性。
你可以在这里找到我项目的所有细节
