简体   繁体   中英

Changing interface into type with module augmentation in Typescript

Is it possible to change interface into type when augmenting modules with TS? I want to enhance Theme in Material-UI with some of my own properties. I created createPalette.d.ts file:

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;
    };
  }
}

Contents of PaletteOptions and Palette interfaces will be almost identical, so I wanted to simplify it a little bit by extracting neutral as external type and come up with something like this:

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 {}
}

It works, but PaletteOptions and Palette are now considered "empty" and I get errors because of no-empty-interfaces rule. After hitting auto-fix ESLint changed it to types:

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;
}

There is no ESLint error, but now module augmentation doesn't work, because Material-UI typings declare PaletteOptions and Palette as interfaces and TS ignores my declarations. What are my options now? Is there any way to trick TS into accepting PaletteOptions and Palette being types or should I just go with eslint-ignore on that rule?

It seems like the rule is assuming that you're not augmenting, and it would be safe to disable it, as you'll need another interface to augment the existing interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM