Best practices for interfaces in Typescript

Here's a question that doesn't have a clear-cut answer. I understand that coding styles vary greatly, especially among different languages - for example, camel case function names in JavaScript vs pascal casing methods in C#. I can definitely accept that.

Although it might be overthinking things, I'm delving into TypeScript and really liking what I see. I plan to use it with Angular2 and want to establish a solid style guide.

One thing that's puzzling me is point 2 here, which advises against using the "I" prefix for interfaces. Up until now, I thought this was almost a universal practice. I have a class called Car, so naturally, the interface name would be ICar. But now I'm conflicted about whether or not to follow this convention.

I'm open to following suggested practices, but this particular one has me unsure which direction to take.

Does anyone know why the common convention of using an "I" prefix for interfaces is discouraged in TypeScript? I understand that you can use any conventions you prefer, but I'm curious if there's a specific reason for deviating from this widely-adopted practice.

Any insights or opinions on this matter will be greatly appreciated!

Answer №1

At one point in time, using "I" as a prefix was popular in Java and C# (and possibly other languages), but it is no longer seen as a best practice. However, changing something that the majority of developers are already accustomed to using can be a challenge.</p>

<p>This trend is similar to hungarian notation, which is widely regarded as a bad practice. Instead of using prefixes, it is recommended to give variables and classes meaningful names. For example, if you have different types of cars, consider making "Car" the universal interface and creating classes like "FancyCar implements Car." This approach allows for more natural and intuitive naming conventions without relying on prefixes. You can read more about this concept here: <a href="http://c2.com/cgi/wiki?IntentionRevealingNames" rel="noreferrer">http://c2.com/cgi/wiki?IntentionRevealingNames</a></p>

<p>Some programming languages like Dart (and others) do not have a strict differentiation between interfaces and classes. In Dart, any class can implement another class, with the class' interface serving as an interface itself.</p>

<p><strong>Update:</strong></p>

<p>Naming variables and classes is often considered one of the most challenging aspects of software development. While there may not be a perfect solution, it is generally agreed among experts that using prefixes for technical reasons is not ideal. Instead, many developers opt for naming conventions such as <code>UserService
, UserServiceImpl, MockUserService. By following consistent naming practices throughout your codebase, you can ensure clarity and maintainability. It's also important to consider the common styles used in the programming language you are working with and adhere to those conventions.

Answer №2

Here is a related question that discusses the confusion surrounding TypeScript coding guidelines for interfaces and classes: Understanding Interface and Class Coding Guidelines in TypeScript

To see my detailed answer, click here:

Key Points to Consider:

  1. The era of Hungarian notation is no longer relevant
  2. The use of prefixes like 'I-' goes against the encapsulation principle
  3. Good names serve as a shield against poorly named elements
  4. Choosing appropriate names can dispel the myth that an interface acts as a contract

Answer №3

One should always adhere to common coding practices and standards in order for their code to be easily understood by others. It is important to follow the conventions set by the language being used to ensure consistency.

When it comes to not using prefixes in interface names, there are several compelling reasons:

  1. Introducing prefixes to explicitly declared interfaces creates confusion as some interfaces will have prefixes while others won't. This inconsistency can make the code less readable and harder to maintain.
  2. The compiler treats types (interfaces) and variables as separate entities, so there is no need to prefix interface names to avoid conflicts with variable names.
  3. Using a prefix like 'I' for interfaces is akin to systems hungarian notation, but it doesn't add any meaningful information to the code for the developer writing it.

Answer №4

Two additional reasons

Organization into Modules As the project expands, it becomes necessary to organize the code into modules. The primary objective of modularization is to define clear contracts and conceal the internal details. These contracts are typically defined using interfaces, leading to the exposure of interfaces and factories in the codebase. It is more user-friendly for module consumers to interact with entities like Users and Credentials rather than IUsers and ICredentials

Alphabetical Sorting For efficient navigation, arranging Interfaces and Classes alphabetically in a file navigator can greatly enhance productivity. When dealing with Users, having entries like User, UserService, and UserImpl grouped together simplifies the search process compared to scrolling through entries starting with I, then C, and finally Service

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to include x-api-key in Angular API request headers

I am attempting to include the x-api-key header in the headers, as shown below: service.ts import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { Observable } from ...

Exploring the location of unit testing within async-await in Angular applications

I have been working with Angular 9+ along with karma test runner and jasmine test framework for my unit tests. My focus is on unit testing only the app component which includes dependency injection: app.component.ts import { Component, EmbeddedViewRef } ...

ngModel Error: Unable to retrieve the 'name' property of an undefined value

I have a JSON file that displays different levels of data, some in regular format and some as arrays as shown below. [![enter image description here][1]][1] However, I keep encountering an error message like the one below: [![enter image description her ...

Challenges when transitioning from Angular 8 to Angular 9

After transitioning from Angular 8 to Angular 9, I encountered the following issues. Despite removing and reinstalling node_modules multiple times, the problems persist: An unhandled exception occurred: Cannot find module 'webpack/lib/ParserHelpers&ap ...

Tips on ensuring a <video> element occupies the full height and width of the screen

I am currently working on an Angular 6 project where I am live streaming a user's webcam to an HTML element. My goal is to simulate the experience of capturing a video or photo on a mobile device. However, the size of the video is currently small. I ...

Prevent users from clicking buttons until all mandatory fields are filled out using react-hook-form

I am seeking guidance on how to dynamically disable a button based on the input values of both Name and State in the given code snippet. Specifically, I want to restrict button functionality until both name and state fields are filled out, regardless of ...

Styles applied in the child component will have a cascading effect on the entire webpage

My webpage is divided into two parts: child1 and child2. Page Hierarchy: Parent Child1 Child2 Here are the CSS styles included in the page: Child1 -> z-index: 1 Child2 -> z-index: 2 What I want to achieve is to add a backdrop to the entire ...

Can an attribute be assigned to an Angular host element without specifying a value?

Exploring the concept of host binding on the input element's readonly attribute, aiming to add the attribute without assigning any value. Even though HTML specifications state that assigning a value may not make a difference as long as the attribute i ...

Encountered a hiccup during the deployment of an Angular application on Heroku

I've been working on deploying an Angular app called "test-app" to Heroku via GitHub and everything seems to be going smoothly, except for setting up the express routing function. I've tried different paths, but Heroku keeps throwing this error: ...

Enhancing Connectivity between Angular and Electron

I'm currently in the process of integrating my Angular application with Electron and I am looking to bind and send messages from Electron to Angular. Below is a snippet of my code: App.module.ts: import { NgxElectronModule } from 'ngx-electron& ...

The type 'Promise<UserCredential>' cannot be assigned to

import React, {createContext, useContext, useEffect, useState, ReactNode} from "react"; import { auth } from '../utils/init-firebase'; import { createUserWithEmailAndPassword } from "firebase/auth" type ButtonProps = { ch ...

Discover the location of items within an array

Currently, I am working with a JSON object that has the following structure. My objective is to determine the index based on ID in order to retrieve the associated value. The indexOf function appears to be suitable for arrays containing single values, but ...

Ensuring that all environmental variables are properly set in Typescript by utilizing interfaces and resolving union to tuple type discrepancies

In order to create a required application env variables file named env.d.ts, I want to ensure that any modifications or additions to it will trigger TypeScript errors and runtime errors for the checkEnv function if a value is not set. To achieve this, I h ...

Ways to dynamically emphasize text within ngFor loop

Within my ngFor loop, I have a set of rows. <div *ngFor="let block of data;"> <div class="class-row"> <div class="left">A Label:</div> <div class="right">{{block.key1}}</div> </div> <div class="clas ...

When transitioning the Next application to Typescript, errors are displayed with JSX, but it functions correctly in the browser

After migrating my Next App from JS to TSX, I noticed that the JSX in my TSX file is showing errors and underlined, even though the app runs fine in the browser. I'm puzzled as to why this inconsistency exists. Can anyone provide assistance in resolvi ...

Mastering GraphQL querying in React using TypeScript

After successfully setting up a graphql and being able to use it in Postmen, here is how it looks: query listByName($name: String!) { listByName(name: $name) { id name sortOrder } } My variable is defined as {"name&quo ...

Snackbar and RTK Query update trigger the error message: "Warning: Cannot update during an existing state transition."

I've built a basic ToDos application that communicates with a NodeJS backend using RTK Query to fetch data, update state, and store cache. Everything is functioning properly as expected with the communication between the frontend and backend. Recently ...

Challenges with Angular observables

Struggling to make observables work has been quite the challenge for me lately. My code now resembles a chaotic battleground rather than the organized structure it once was. The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" ...

Tips for exporting/importing only a type definition in TypeScript:

Is it possible to export and import a type definition separately from the module in question? In Flowtype, achieving this can be done by having the file sub.js export the type myType with export type myType = {id: number};, and then in the file main.js, i ...

The 'formGroup' property cannot be bound as it is not recognized as a valid property of 'form' in Angular 7

I tried implementing a login feature using web API with Angular 7, but encountered an error when using <form [formGroup]="loginForm" (submit)="loginFormSubmit()">. What could be causing this issue? https://i.sstatic.net/3M2a5.jpg login.component.ht ...