[英]Changing interface into type with module augmentation in Typescript
Is it possible to change interface
into type
when augmenting modules with TS?使用 TS 扩充模块时是否可以将interface
更改为type
? I want to enhance Theme in Material-UI with some of my own properties.我想用我自己的一些属性来增强 Material-UI 中的主题。 I created createPalette.d.ts
file:我创建了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;
};
}
}
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: PaletteOptions
和Palette
接口的内容几乎相同,所以我想通过提取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 {}
}
It works, but PaletteOptions
and Palette
are now considered "empty" and I get errors because of no-empty-interfaces
rule.它可以工作,但是PaletteOptions
和Palette
现在被认为是“空的”,并且由于no-empty-interfaces
规则而出现错误。 After hitting auto-fix ESLint changed it to types:在点击自动修复 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;
}
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.没有 ESLint 错误,但现在模块扩充不起作用,因为 Material-UI 类型PaletteOptions
和Palette
声明为接口,而 TS 忽略了我的声明。 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?有什么办法可以诱使 TS 接受PaletteOptions
和Palette
是类型,还是我应该只是 go 和eslint-ignore
在该规则上?
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.似乎该规则假设您没有进行扩充,并且禁用它是安全的,因为您需要另一个界面来扩充现有界面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.