typescript - 如何强制对象的孩子成为某个接口或从该接口扩展?
问题描述
我想强制对象的孩子成为某个接口或从这个接口扩展。
例如:
export interface Configuration {
pages: {
home: IHome;
about: IAbout; // I want IAbout will have to extends IPage
contact: IPage;
};
}
interface IPage {
displayName: string;
}
interface IHome extends IPage {
slider: any; // property that only Home has
}
interface IAbout { // How to force this interface to extends IPage like IHome interface
map: any; // property that only About has
}
我该如何IAbout
强制extends IPage
?
我知道方法[pageName: string]: IPage
,但它不会IPage
强迫extends IPage
。
有没有办法强制这些值继承自IPage
?
解决方案
我猜你的意思是每个嵌套对象都是给定的接口和 IPage 接口。
您可以将交集与 IPage 和映射对象与计算键一起使用。
type ChildrenWithIPage<T extends object> = {
[key in keyof T]: T[key] & IPage;
};
export interface Configuration {
pages: ChildrenWithIPage<{
home: IHome;
about: IAbout;
contact: IPage;
}>;
}
interface IPage {
displayName: string;
}
interface IHome {
slider: any;
}
interface IAbout {
map: any;
}
using[key in keyof T]
将遍历 T 的所有键,T[key]
将返回 property 中的值key
,并& IPage
创建一个交集,其行为非常类似于接口的继承
推荐阅读
- python - openpyxl 从特定列/单元格开始写入
- vue.js - Vuex,具有全局错误和通知处理的最佳实践
- powershell - PowerShell:字符串到日期时间,但采用欧洲格式
- powerbi - 如何使用 puppeteer 挂钩到 powerbi 报告加载事件
- ios - 创建反应原生模块并在应用程序中使用它
- r - 如何使用向量中的两个条件在 r 中运行 for 循环
- android - 使用融合位置提供程序获取用户当前位置
- javascript - 如何生成特定真实世界大小的图像
- angular - 带有 ResizeObserver 的 ViewContainerRef 在角度中无法正常工作
- angular - 当另一个发射时运行一个可观察的,返回两个结果