typescript - 检查json属于哪个扩展接口
问题描述
我有一个由其他两个接口扩展的父接口
interface ParentItem {
foo: number;
}
interface ChildItemOne extends ParentItem {
fooone: string;
}
interface ChildItemTwo extends ParentItem {
footwo : string;
}
我有一个接受 ParentItem 的函数,我如何确定它是属于 ChildItemOne 还是 ChildItemTwo
if(obj.footwo) or if(obj.fooone) // obj = ParentItem obj
导致错误,因为 footwo 或 fooone 不是 ParentItem 的一部分
解决方案
你可以这样做:
使用联合类型ChildItemOne | ChildItemTwo
作为参数并检查一个属性是否是对象的一部分......
function suggestion1 (baz: ChildItemOne | ChildItemTwo) {
if('fooone' in baz) {
baz.fooone;
// baz is ChildItemOne
} else {
baz.footwo;
// baz is ChildItemTwo
}
}
...或使用泛型类型ParentItem
作为参数并定义类型保护函数。
function suggestion2 (baz: ParentItem) {
if(isItemOne(baz)) {
baz.fooone;
} else if(isItemTwo(baz)) {
baz.footwo;
}
}
function isItemOne (obj: ParentItem): obj is ChildItemOne {
return 'fooone' in obj;
}
function isItemTwo (obj: ParentItem): obj is ChildItemTwo {
return 'footwo' in obj;
}
推荐阅读
- css - 修改了父主题css,如何将这些更改推送到子主题?
- node.js - ImageMagick:不使用文件的 PDF 到 PNG nodejs?
- javascript - 将一些对象键映射到对象中
- javascript - 如何禁止添加元素
- rpgle - RPGLE 嵌入式 SQL“从最终表中选择...”在编译时抛出 SQL0029
- python - 在 Python 中格式化日期
- ruby - 附加到字符串时,为什么我的三元运算符需要括号?
- java - 如何在不先渲染的情况下将 android 视图渲染到画布(即没有完整布局)
- json - Swift 结构体作为请求体
- meson-build - 如何让介子确定 Windows 操作系统上的动态链接器?