Home > Net >  TypeScript eslint: Rule to prevent same naming of interface
TypeScript eslint: Rule to prevent same naming of interface

Time:06-29

In TypeScript defining multiple interfaces with same name is allowed:

export interface Person {
  fullName: string;
}

export interface Person {
  name: string;
}

Is there an eslint rule to give a warning when this is encountered?

CodePudding user response:

I don't think this is possible as this is a core feature of TS.

CodePudding user response:

You have declared an interface. Interfaces are great for declaring what properties and functions the outside world can see on an object. What they don't do is allow you you to add any implementation detail. The implementation detail either comes in the forms of functions or classes. You currently have a function, but want to implement it on the object itself. For that you can create a class that implements the interface. I would recommend that you keep your interface, and pass that around where possible. The code that consumes an IPersonItem doesn't care how fullName has been implemented, just that it exists.

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

Some example usage

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"
  }
}
  • Related