首页 > 解决方案 > 如何强制对象的孩子成为某个接口或从该接口扩展?

问题描述

我想强制对象的孩子成为某个接口或从这个接口扩展。
例如:

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

标签: typescripttypescript-typings

解决方案


我猜你的意思是每个嵌套对象都是给定的接口和 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创建一个交集,其行为非常类似于接口的继承


推荐阅读