【问题标题】:Changing interface into type with module augmentation in Typescript在 Typescript 中使用模块扩充将接口更改为类型
【发布时间】:2020-10-18 15:12:21
【问题描述】:

在使用 TS 扩充模块时,是否可以将 interface 更改为 type? 我想用我自己的一些属性来增强 Material-UI 中的主题。我创建了createPalette.d.ts 文件:

import '@material-ui/core/styles/createPalette';

declare module '@material-ui/core/styles/createPalette' {
  export interface PaletteOptions {
    neutral?: {
      moderate: string;
      dark: string;
    };
  }
  export interface Palette {
    neutral: {
      moderate: string;
      dark: string;
    };
  }
}

PaletteOptionsPalette 接口的内容几乎相同,所以我想通过将neutral 提取为外部类型来简化它,并提出如下内容:

import '@material-ui/core/styles/createPalette';

type CustomPalette = {
  neutral: {
    moderate: string;
    dark: string;
  };
};

declare module '@material-ui/core/styles/createPalette' {
  export interface PaletteOptions extends Partial<CustomPalette> {}
  export interface Palette extends CustomPalette {}
}

它可以工作,但 PaletteOptionsPalette 现在被视为“空”,并且由于 no-empty-interfaces 规则而出现错误。点击自动修复 ESLint 后将其更改为类型:

import '@material-ui/core/styles/createPalette';

type CustomPalette = {
  neutral: {
    moderate: string;
    dark: string;
  };
};

declare module '@material-ui/core/styles/createPalette' {
  export type PaletteOptions = Partial<CustomPalette>;
  export type Palette = CustomPalette;
}

没有 ESLint 错误,但现在模块扩充不起作用,因为 Material-UI 类型将 PaletteOptionsPalette 声明为接口,而 TS 忽略了我的声明。 我现在有什么选择?有什么办法可以诱使 TS 接受 PaletteOptionsPalette 是类型,还是我应该按照该规则使用 eslint-ignore

【问题讨论】:

    标签: javascript typescript material-ui


    【解决方案1】:

    这条规则似乎假设您没有进行扩充,禁用它是安全的,因为您需要另一个界面来扩充现有界面。

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 2021-08-07
      • 2015-04-01
      • 2018-06-23
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      相关资源
      最近更新 更多