[英]typescript/eslint rule for function syntax in objects implementing interface
[英]TypeScript eslint: Rule to prevent same naming of interface
在 TypeScript 中定義多個具有相同名稱的接口是允許的:
export interface Person {
fullName: string;
}
export interface Person {
name: string;
}
遇到這種情況時是否有 eslint 規則發出警告?
我認為這是不可能的,因為這是 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"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.