Could you please share the standard naming convention used for interfaces and classes in TypeScript?

Here's what I have:

interface IUser {
  email: string
  password: string
}

class User {
  email: string
  password: string
  constructor(email: string, password: string) {
    this.email = email
    this.password = password
  }

  isEmailValid(): boolean {
    return validatorJs.isEmail(this.email)
  }

  isPasswordValid(): boolean {
    return validatorJs.isStrongPassword(this.password, opts)
  }
}

function createUser(user: IUser) {
  // applying isPasswordValid and isEmailValid
  //insert ...
}

function getUser(): IUser {
  return new User('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e2ebebc4e6e5f6aae7ebe9">[email protected]</a>', 'foobar')
}

In the interface name, should I include the letter "I" before it or is there a better way to do it?

Answer №1

There is a newly developed TypeScript style guide available for reference at this link:

The guide includes rules and best practices inspired by Google's own style guide for the TypeScript language. It is suggested to choose guidelines that align with your team's needs.

One specific point from the guide addresses interface naming:

Avoid using special markers in interface names (e.g. IMyInterface or MyFooInterface) unless it is commonly practiced in your development environment. Instead, when creating an interface for a class, give it a name that clearly reflects the purpose of the interface (for example, class TodoItem and interface TodoItemStorage if the interface defines the format for storage/serialization in JSON).

Answer №2

In the TypeScript community, there is no official naming convention for interfaces, but it's generally recommended not to use I as a prefix unless the interface is specifically meant to be implemented by classes. For example:

import type { IUser } from '$models/interfaces/iuser.interface';
import type { IDeserializable } from '$models/interfaces/ideserializable.interface';

export class UserModel implements IDeserializable<IUser>, IUser {
  public email: string;
  public password: string;

  deserialize(input: IUser): this {
    Object.assign(this, input);
    return this;
  }
}

(This approach was inspired by the sveltekit-starter project by Navneet Sharma.)

Ultimately, the choice of naming method for interfaces is up to your own discretion.

Answer №3

Opinions vary when it comes to naming conventions in Microsoft software. You can find the official guidelines here, but here is a common approach:

  1. Class names should be nouns and written in PascalCase
  2. Interfaces should also use PascalCase (avoid prefixing with 'I')
  3. Enums and their fields are both in PascalCase
  4. Variables (let/const) are typically in camelCase. Sometimes constants may be in UPPERCASE.

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

How can I display data both as a dropdown and an autocomplete in Angular using a textbox?

There is a textbox with autocomplete functionality. When the user clicks on the textbox, an API call is made with two parameters - Pubid and Date. The data is then displayed in a dropdown with autocomplete feature. Now I am attempting to have the data app ...

What steps should I take in order to correctly implement the onChange event and retrieve the event.target.value in my

Incorporating useForm, yupResolver, and Yup for validation caused issues with the previously functioning handleChange function. The value variable doesn't log anything when console.logged, indicating a disconnect with the input field content. Addition ...

Tips for adjusting the position of nodes that are overlapping in React Flow

Whenever node1 is moved over node2 in react-flow, they end up overlapping. I am looking to shift node2 towards the right to avoid this overlap. The desired outcome is for node2 to be shifted to the right side. ...

Error when running end-to-end tests in Angular CLI using the ng e2e

Recently, I created a new Angular 4 project using the Angular CLI. Upon running ng e2e, the sample end-to-end test worked flawlessly. However, when I later added a subfolder named services in the app folder and generated a service within it, the ng e2e com ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

Here is a guide on showcasing information obtained from ASP.NET API in Angular version 13

My goal is to fetch motorcycle data from a web API and showcase it in my Angular project. ASP.NET Framework Web API 4.7 Angular CLI: 13.3.7 Angular: 13.3.11 On the Web API end: Controller: [EnableCors(origins: "*", headers: "*", ...

What is the process of using TypeScript to import a constant exported in JavaScript?

In the environment I'm using typescript 2.6.1. Within react-table's index.js file, there is a declaration that looks like this: import defaultProps from './defaultProps' import propTypes from './propTypes' export const React ...

The color syntax in the text editor of Visual Studio 2022 is being lost when casting an interface

After attempting to cast an interface, the entire code turns white. let object : someInterface = <someInterface> someUnknownHapiRequestPayload View a screenshot of the text editor here I have already tried common troubleshooting steps such as updat ...

Combining two streams in RxJS and terminating the merged stream when a particular input is triggered

I am currently developing an Angular application and working on implementing a system where an NGRX effect will make requests to a service. This service will essentially perform two tasks: Firstly, it will check the local cache (sqlite) for the requested ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...

AOT compile error due to Angular interpolation syntax

I am facing an issue while compiling my application. The AOT compiler is showing an error related to Angular interpolation in an Angular 2 form: Property 'address' does not exist on type 'FirebaseObjectObservable'. Here's a sn ...

What are the steps to organize an array of objects by a specific key?

Experimented with the following approach: if (field == 'age') { if (this.sortedAge) { this.fltUsers.sort(function (a, b) { if (b.totalHours > a.totalHours) { return 1; } }); this ...

The Zoom-sdk functions properly on a local machine, but encounters issues when it is

Using zoom's API, jwt, and the websdk, I am able to create a meeting on button click, join as a host, and start the meeting for others to join. This process works flawlessly when running locally, but once deployed to Cloudflare, I encounter the follow ...

An issue has been detected with the width attribute in Typescript when using

I have a question regarding the TypeScript error related to the width property. I've created a component called ProgressBar where I'm using Stitches for styling. However, TypeScript is throwing an error even when I specify the type as ANY. impor ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

What is the correct way to utilize the mapState function within a TypeScript environment while implementing Vuex?

In my Vue.js project integrated with Vuex, I am using Typescript syntax. While trying to use the mapState method as computed in my .ts file, I encountered a syntax error. Currently, I am following the suggested syntax for computed function in the documenta ...

Guide to transmitting a "token" to an "API" using "React"

As a novice developer, I am facing a challenge. When users log in to our website, a JWT is created. I need to then pass this token to the API on button click. If the backend call is successful, the API response should be displayed. If not, it should show ...

Create an array of arrays within a loop using TypeScript

My application contains an object with dates and corresponding time arrays. The console log output is displayed below: 32: { 1514160000: Array [ 1200, 1500 ], 1514764800: Array [ 1200, 1500 ], 1515369600: Array [ 1200, 1500 ], 1515974400: Array [ 700, 12 ...

verifying the date in a specific moment

Is there a way to validate the date accurately? to determine whether she cleared it or not. I've exhausted all my options. Despite reading through the documentation, I am unable to get it right. Here is what I attempted: if ('2023-03-03 ...

I am able to view the node-express server response, but unfortunately I am unable to effectively utilize it within my Angular2 promise

https://i.stack.imgur.com/d3Kqu.jpghttps://i.stack.imgur.com/XMtPr.jpgAfter receiving the object from the server response, I can view it in the network tab of Google Chrome Dev Tools. module.exports = (req, res) => { var obj = { name: "Thabo", ...