typescript - Typescript:基于属性值的类型确定
问题描述
我很确定 Typescript 能够根据属性值确定扩展类,例如:
interface Base {
type: string;
child?: Base;
}
interface Ext extends Base {
type: 'test';
sth: string;
}
z({
type: 'a',
child: {
type: 'b',
}
}); // ok
z({
type: 'a',
child: {
type: 'test',
sth: 'val'
}
}); // not ok
function z(input: Base) { }
上面的例子不起作用,TS 告诉我sth
interface 上不存在属性Base
。由于属性上Ext
的值,我需要更改什么以便 TS 将孩子理解为实际上是 type of ?'test'
type
解决方案
您需要将其声明为类型Ext
并且它应该通过
let x: Ext = {
type: 'test',
sth: 'value'
}
推荐阅读
- html - 带有flex子元素的div的CSS绝对像素高度
- android - 在Android应用中添加优酷播放器库
- android - 添加 setOnClickListener 后模拟器中的“应用程序保持停止”
- python - Odoo 10:扩展现有模块以显示新菜单项
- firebase - 如何从 Firebase 存储启用 gzip 压缩?
- reactjs - 收到此错误:TypeError:无法读取 null 的属性“setMaxNumberPointsPerLink”
- angular - 打字稿中的类和接口之间的理解缺失
- html - css中的动态动画滚动速度
- ruby-on-rails - 如何准确删除一个 has_and_belongs_to_many 关联?
- bash - 从输入中获取文件夹名称的正确方法