Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming abstract classes and Interfaces in TypeScript [closed]

Tags:

There are debates and no consistency in this question, so I want to clarify naming standards for class, file names, suffixes and others for typescript. I want to know, how you name abstract classes, interfaces and logically organize code in your Typescript projects?

Possible solutions:

For interfaces:

  • with "I" as a prefix
  • with "Interface" as a suffix
  • with nothing added at all

For abstract classes:

  • with "Abstract" as prefix
  • something like "Base" as a prefix
  • with nothing at all

Example with C#

public class User : AbstractUser, IUser

Same in Java and PHP

public class User extends AbstractUser implements UserInterface

And in Typescript

export class User extends AbstractUser implements UserInterface

This is the normal approach used in frameworks based on languages such as C#, Java and modern PHP7+


Microsoft is recommending add "Interface" as a suffix, which for me is correct. https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Interfaces.md#class-types

Another popular style guide is suggesting not to add any suffixes for prefixes to interfaces, for me violates the rules, readability and overall looks wrong. https://basarat.gitbooks.io/typescript/content/docs/styleguide/styleguide.html#interface

export class User extends AbstractUser implements User
like image 995
Ivan Proskuryakov Avatar asked Jan 29 '17 21:01

Ivan Proskuryakov


1 Answers

I think this is a matter of taste.

I'd use interface name User instead of IUser or UserInterface if a user object can be described by plain JSON, thus being a pure data object with no class-like behavior. Because you might never need an implementing class, you can always use object literals:

interface User {
    name: string;
    email: string;
}

function createDummyUser(): User {
    return {
        name : "Alice",
        email: "[email protected]"
    }
}

I'd use the plain name of the abstract class of objects (like 'Car') and use a specific name for the non-abstract class (like 'Beetle'). You can ensure your abstract implementation is not used by mistake by making the constructor protected:

class Car {
    protected constructor() {
    }
}

const fail = new Car();  // error because c'tor is protected

class Beetle extends Car {
       public constructor(){
           super();
       }
}

let itBe = new Beetle();  // here we go!
like image 167
Benjamin Avatar answered Sep 22 '22 11:09

Benjamin