在C ++中,动态转换会在运行时检查对象是否实现和接口,并返回nullptr
而不是对象,否则返回interface MyInterface {
value: string;
lastUpdated: number;
deleted: boolean;
}
let obj = JSON.parse(inputdata);
if ('value' in obj && 'lastUpdated' in obj && 'deleted' in obj && typeof obj.value === 'string' && obj.lastUpdated === 'number' && obj.deleted === 'boolean') {
// do something
} else {
// null case
}
。
如何在TypeScript中执行相同的操作。我能想到的方法是检查每个属性的存在和类型:
{{1}}
由于TypeScript接口在运行时不可用,我什至无法编写帮助程序函数来概括这些检查。
在TypeScript中是否有更好的动态转换方法?
答案 0 :(得分:3)
如果您实施type guard
,我相信您会得到您所需要的interface MyInterface {
value: string;
lastUpdated: number;
deleted: boolean;
}
function isMyInterface(obj: any): obj is MyInterface {
// You don't really need the first three, just the last three
return 'value' in obj &&
'lastUpdated' in obj &&
'deleted' in obj &&
typeof obj.value === 'string' &&
typeof obj.lastUpdated === 'number' &&
typeof obj.deleted === 'boolean';
}
let obj = JSON.parse(inputdata);
if (isMyInterface(obj)) {
// do something, compiler knows obj is a MyInterface in this block
} else {
// null case
}