TypeScript eslint:防止接口同名的规则



在TypeScript中,允许使用相同的名称定义多个接口:

export interface Person {
fullName: string;
}
export interface Person {
name: string;
}

是否有eslint规则在遇到这种情况时给出警告?

TypeScript -eslint关闭此检查以添加对TypeScript函数重载和声明合并的支持。您可以通过重新启用no-redeclare:

在您自己的规则中重写以重新打开它。
module.exports = {
"rules": {
"@typescript-eslint/no-redeclare": "off",
"no-redeclare": "warn",
}
};

我们选择打开这个是为了避免错误,同时理解当我们想要有意合并接口时,我们总是可以在文件或块级别忽略它。

详情见https://typescript-eslint.io/rules/no-redeclare/

我认为这是不可能的,因为这是TS的核心功能。

你声明一个接口。接口的声明属性和函数外面的世界可以看到在一个对象。它们不允许你添加任何实现细节。实现细节以函数或类的形式出现。您当前有一个函数,但希望在对象本身上实现它。为此,您可以创建一个实现该接口的类。我建议您保留您的接口,并尽可能将其传递出去。使用IPersonItem的代码并不关心fullName是如何实现的,只关心它的存在。

export interface IPersonItem {
_id?: number;
name: string;
lastName: string;
fullName: string;
}
export class PersonItem implements IPersonItem {
constructor(
public name: string,
public lastName: string,
public _id?: number
) {
}
get fullName() { return `${this.name} ${this.lastName}`; }
}

一些示例用法

export class MyService {
getPersonItem(): IPersonItem {
return new PersonItem('first', 'last', 123);
}
}
export class MyComponent {
constructor(private myService: MyService) {}
ngOnInit() {
const person: IPersonItem = this.myService.getPersonItem();
console.log(person.fullName); // "first last"
}
}

最新更新