149

I read through the TypeScript Coding guidelines

And I found this statement rather puzzling:

Do not use "I" as a prefix for interface names

I mean something like this wouldn't make a lot of sense without the "I" prefix

class Engine implements IEngine

Am I missing something obvious?

Another thing I didn't quite understand was this:

Classes

For consistency, do not use classes in the core compiler pipeline. Use function closures instead.

Does that state that I shouldn't use classes at all?

Hope someone can clear it up for me :)

5
  • 22
    To clarify, this is the documentation about the style of the code for TypeScript, and not a style guideline for how to implement your project. If using the I prefix makes sense to you and your team, USE IT. If not, maybe the Java style of SomeThing (interface) with SomeThingImpl (implementation) then by all means use that.
    – Brocco
    Aug 7, 2015 at 12:11
  • 4
    The beauty of coding guidelines is that they are guidelines, so you can choose to implement them or not. Personally I use I to denote an interface because it is what I'm used to and it makes sense to people in my team.
    – Jon Preece
    Aug 7, 2015 at 14:01
  • 2
    Yes they're just guidelines. But most of the time there is a good reason behind the guideline. So just sticking to what you're used to doesn't develop you as a programmer :)
    – Snæbjørn
    Aug 7, 2015 at 14:17
  • 6
    When my team started using TS we also used I-prefix for interfaces. C# influence, I assume. Then I read TypeScript team's guideline about not using I-prefix. It took me several weeks to realize it. I was eagerly searching for information why they have such rule. After a time I realized: I-prefix for interfaces is a flaw (at least in TypeScript), it causes more problems than provides benefits. Nov 29, 2017 at 7:36
  • 2
    @StanislavBerkov Sorry, I know this is oooold, but care to elaborate please? On this specifically: After a time I realized: I-prefix for interfaces is a flaw (at least in TypeScript), it causes more problems than provides benefits.
    – matronator
    Jul 20, 2022 at 20:53

9 Answers 9

297

When a team/company ships a framework/compiler/tool-set they already have some experience, set of best practices. They share it as guidelines. Guidelines are recommendations. If you don't like any you can disregard them. Compiler still will compile your code. Though when in Rome...

This is my vision why TypeScript team recommends not I-prefixing interfaces.

Reason #1 The times of the Hungarian notation have passed

Main argument from I-prefix-for-interface supporters is that prefixing is helpful for immediately grokking (peeking) whether type is an interface. Statement that prefix is helpful for immediately grokking (peeking) is an appeal to Hungarian notation. I prefix for interface name, C for class, A for abstract class, s for string variable, c for const variable, i for integer variable. I agree that such name decoration can provide you type information without hovering mouse over identifier or navigating to type definition via a hot-key. This tiny benefit is outweighed by Hungarian notation disadvantages and other reasons mentioned below. Hungarian notation is not used in contemporary frameworks. C# has I prefix (and this the only prefix in C#) for interfaces due to historical reasons (COM). In retrospect one of .NET architects (Brad Abrams) thinks it would have been better not using I prefix. TypeScript is COM-legacy-free thereby it has no I-prefix-for-interface rule.

Reason #2 I-prefix violates encapsulation principle

Let's assume you get some black-box. You get some type reference that allows you to interact with that box. You should not care if it is an interface or a class. You just use its interface part. Demanding to know what is it (interface, specific implementation or abstract class) is a violation of encapsulation.

Example: let's assume you need to fix API Design Myth: Interface as Contract in your code e.g. delete ICar interface and use Car base-class instead. Then you need to perform such replacement in all consumers. I-prefix leads to implicit dependency of consumers on black-box implementation details.

Reason #3 Protection from bad naming

Developers are lazy to think properly about names. Naming is one of the Two Hard Things in Computer Science. When a developer needs to extract an interface it is easy to just add the letter I to the class name and you get an interface name. Disallowing I prefix for interfaces forces developers to strain their brains to choose appropriate names for interfaces. Chosen names should be different not only in prefix but emphasize intent difference.

Abstraction case: you should not not define an ICar interface and an associated Car class. Car is an abstraction and it should be the one used for the contract. Implementations should have descriptive, distinctive names e.g. SportsCar, SuvCar, HollowCar.

Good example: WpfeServerAutosuggestManager implements AutosuggestManager, FileBasedAutosuggestManager implements AutosuggestManager.

Bad example: AutosuggestManager implements IAutosuggestManager.

Reason #4 Properly chosen names vaccinate you against API Design Myth: Interface as Contract.

In my practice, I met a lot of people that thoughtlessly duplicated interface part of a class in a separate interface having Car implements ICar naming scheme. Duplicating interface part of a class in separate interface type does not magically convert it into abstraction. You will still get concrete implementation but with duplicated interface part. If your abstraction is not so good, duplicating interface part will not improve it anyhow. Extracting abstraction is hard work.

NOTE: In TS you don't need separate interface for mocking classes or overloading functionality. Instead of creating a separate interface that describes public members of a class you can use TypeScript utility types. E.g. Required<T> constructs a type consisting of all public members of type T.

export class SecurityPrincipalStub implements Required<SecurityPrincipal> {
  public isFeatureEnabled(entitlement: Entitlement): boolean {
      return true;
  }
  public isWidgetEnabled(kind: string): boolean {
      return true;
  }

  public areAdminToolsEnabled(): boolean {
      return true;
  }
}

If you want to construct a type excluding some public members then you can use combination of Omit and Exclude.

18
  • 7
    I like your point on naming concrete classes more specific than interface names but think the I prefix is helpful for immediately grokking whether type has an implementation or not. The major advantage to using interfaces is to not couple the implementation details of external code to a specific implementation. May 24, 2017 at 18:52
  • 3
    @demisx if it feels awkward then you should not do it. Answer the question: do you really need them? Do they make any sence or you use them just for false sense of doing the right engineering? Feb 28, 2018 at 11:15
  • 3
    While your points sound good in theory, the reality is the "I" prefix is often traded for the "Impl" suffix instead in large enough teams
    – jameslk
    Aug 7, 2018 at 21:59
  • 6
    @jameslk I know naming things without I and Impl is hard ("There are only two hard things in Computer Science: cache invalidation and naming things" -- Phil Karlton) but is doable. Aug 8, 2018 at 8:05
  • 6
    I agree that removing I is usually replaced by adding a prefix or suffix to the implementations: DefaultFooService or FoodServiceImpl. WIth prefix, you get grokking and no overlapping naming problems between contracts and implementations/abstractions. Also the point on repeating is valid, but the point of interfaces is having contracts, and being able to replace the implementation with something else. Usually this is absolutely crucial in unit testing... not to mention the benefits of the abstractions and immutability and so on.. I'm all for the interfaces I prefixes.
    – karczilla
    Dec 19, 2018 at 19:42
59

Clarification regarding the link that you reference:

This is the documentation about the style of the code for TypeScript, and not a style guideline for how to implement your project.

If using the I prefix makes sense to you and your team, use it (I do).

If not, maybe the Java style of SomeThing (interface) with SomeThingImpl (implementation) then by all means use that.

6
  • 31
    Just for clarification. Typescript handbook still says: In general, do not prefix interfaces with I (e.g. IColor). Because the concept of an interface in TypeScript is much more broad than in C# or Java, the IFoo naming convention is not broadly useful. It is not strict, but looks like strong recommendation.
    – Guria
    Mar 21, 2016 at 8:45
  • 4
    Agree. It does sound like a code guideline from Microsoft for all TypeScript based projects, not just the TypeScript itself. We found this guideline very confusing and still prefix all interfaces with "I".
    – demisx
    Aug 10, 2016 at 15:58
  • 4
    There is scenario that I think make sense to keep I. In a React project have Card which is an interface and a component called Card. In the props I need an array of Card, but the type not the component. I have to choose to name ICard or CardComponent...
    – BrunoLM
    Apr 9, 2017 at 18:06
  • 5
    SomeThingImpl implements SomeThing is as good as SomeThing implements ISomeThing. If SomeThing is an abstraction then naming should be Concrete[Some]Thing implements SomeThing. Nov 27, 2017 at 10:14
  • As said by @Guria, I think TypeScript handbook says it all, we just have to pay attention to the examples and we'll know how to use it well. Dec 14, 2018 at 19:00
6

I find @stanislav-berkov's a pretty good answer to the OP's question. I would only share my 2 cents adding that, in the end it is up to your Team/Department/Company/Whatever to get to a common understanding and set its own rules/guidelines to follow across.

Sticking to standards and/or conventions, whenever possible and desirable, is a good practice and it keeps things easier to understand. On the other side, I do like to think we are still free to choose the way how we write our code.

Thinking a bit on the emotional side of it, the way we write code, or our coding style, reflects our personality and in some cases even our mood. This is what keeps us humans and not just coding machines following rules. I believe coding can be a craft not just an industrialized process.

2

I personally quite like the idea of turning a noun into an adjective by adding the -able suffix. It sounds very impropper, but I love it!

interface Walletable {
  inPocket:boolean
  cash:number
}


export class Wallet implements Walletable {
  //...
}

}

3
  • 19
    But.. a wallet isn't walletable - things you put in your wallet are walletable.
    – jKlaus
    Oct 20, 2021 at 16:38
  • Walletlike could be better.
    – Adam
    Dec 18, 2022 at 20:57
  • How about calling the interface Wallet and its implementations LeatherWallet, RFIDWallet, and Checkbook? Sep 22 at 13:28
2

I do like to add a Props suffix.

interface FormProps {
 some: string;
}

const Form:VFC<FormProps> = (props) => {
  ...
}

2

The guidelines that are suggested in the Typescript documentation aren't for the people who use typescript but rather for the people who are contributing to the typescript project. If you read the details at the beginning of the page, it clearly defines who should use that guideline. Here is a link to the guidelines. Typescript guidelines

In conclusion as a developer you can name you interfaces the way you see fit.

1

I'm trying out this pattern similar to other answers, but exporting a function that instantiates the concrete class as the interface type, like this:

export interface Engine {
  rpm: number;
}

class EngineImpl implements Engine {
  constructor() {
    this.rpm = 0;
  }
}

export const createEngine = (): Engine => new EngineImpl();

In this case the concrete implementation is never exported.

0

The type being an interface is an implementation detail. Implementation details should be hidden in API:s. That is why you should avoid I.

You should avoid both prefix and suffix. These are both wrong:

  • ICar
  • CarInterface

What you should do is to make a pretty name visible in the API and have a the implemtation detail hidden in the implementation. That is why I propose:

  • Car - An interface that is exposed in the API.
  • CarImpl - An implementation of that API, that is hidden from the consumer.
5
  • Currently I utilize this structure as well which was established from my SpringBoot background. So this is considered proper in TS? There appears to be a lot of opinions in the TS community on what is proper with no definitive answer.
    – Impurity
    Jan 13, 2020 at 2:19
  • 2
    Using the Impl suffix will have the side effect of replacing whichever know-it-all is berating you for the I prefix with Uncle Bob. Apr 1, 2020 at 16:07
  • 3
    Avoiding suffix in interface just to add it everywhere to implementation? And what if you decide to remove interface for this class? Will you leave Impl or remove that as well? Mar 19, 2021 at 10:27
  • 1
    If I decide to remove the interface, I use the Car name for the class. It is an example of what you can do when you dont expose implementation details such as ICar and CarInterface. Mar 19, 2021 at 18:36
  • Ok so you have a type CartItem and a CartItem component which takes a CartItem as props. It's not possible what you suggest here you need some kind of suffix or prefix.
    – Ini
    Jun 12, 2022 at 19:45
0

If you want to implement a clean architecture, in some situations, and in my opinion of course, it really makes sense to use the I prefix ...

For example, imagine you want all your business objects to be auditable (ie have createdBy, createdAt etc fields).

You'll probably end up with in your domain package:

export interface MyInterface {
     createdDate : Date;
     ....
}

export class AuditableModel implements MyInterface{
     createdDate : Date;
     ....
}

and in your infrastructure package you'll probably have :

export class AuditableDbEntity implements MyInterface {
    @Property()
    createdDate: Date = new Date();
    ...
}

So what should MyInterface be named ? In my opinion, IAuditable is a good name for this. I'm struggling to find a name that would make more sense.


This is different from the situation where you define a service in your domain :

export interface Logger {
    log(msg:string)
}

and in your infrastructure a concrete implementation that will be injected in the domain :

export class ConsoleLogger implements Logger {
      log(msg:string){
           console.log(msg)
      }
}

Here, the interface being a straight "Logger" forces the implementer to find a better name for the implementation (ie ConsoleLogger and not just Logger)


In the end, I use a I prefix everywhere in order to stay coherent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.