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

Exploring the visitor design pattern with numerical enumerated types

I am exploring the use of the visitor pattern to ensure comprehensive handling when adding a new enum value. Here is an example of an enum: export enum ActionItemTypeEnum { AccountManager = 0, Affiliate = 4, } Currently, I have implemented the fol ...

Angular Bootstrap Datepicker provides us with a date object, but I need it in the Date format

My desired date format is "Wed Aug 07 2019 16:42:07 GMT+0530 (India Standard Time)", but instead I am receiving { year: 1789, month: 7, day: 14 } from ngbDatepicker. Any assistance on resolving this issue would be greatly appreciated. ...

What strategies can be employed to improve generic inference skills?

Looking at the scenario provided below, how can we enhance code reusability in a manner similar to foobarA? interface F<T, U extends string> { t: T, f: (u: U) => void } declare const foo: <T, U extends string>(type: U) => F<T, U>; ...

The 'wrapper' property is not present in the 'ClassNameMap<never>' type in Typescript

Hey there, I've been encountering a puzzling issue in my .tsx file where it's claiming that the wrapper doesn't exist. My project involves Material UI and Typescript, and I'm relatively new to working with Typescript as well as transiti ...

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

Switching the Checkbox Data Binding Feature in Angular

I am looking to send a value based on a toggle switch checkbox selection between Hourly or Salary. How can I incorporate this into the form below? html <div class="row"> <div class="col-sm-6"> <div cl ...

NGXS Alert: Unable to resolve parameters for TranslationEditorState: (?)

I'm currently implementing NGXS for state management within my Angular 9 application. I've encountered a specific issue where any attempt at dependency injection in one of the state classes results in an error message stating "Error: Can't r ...

Error Message: The Query<DocumentData> type cannot be assigned to the DocumentReference<DocumentData> parameter

Currently, I am attempting to execute a query against Firestore data. Here is my code snippet: import { collection, getDoc, query, where } from "firebase/firestore"; import { db } from "../../utils/firebaseConfig"; const getQuery = a ...

What steps can I take to enhance the quality of my PDF files? Currently, I am utilizing Jspdf in conjunction with html

My current challenge involves generating a PDF file from my application. Although I am able to create a PDF, the quality is not up to par. When I download the PDF, I notice some discrepancies in text quality. While it's not terrible, it's also n ...

Using `this` within an object declaration

I am encountering an issue with the following code snippet: const myObj = { reply(text: string, options?: Bot.SendMessageOptions) { return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options }) ...

Excluding certain source files in Typescript's tsconfig is a common practice to

My attempt to configure Typescript to exclude specific files during compilation is not working as expected. Despite setting exclusions in my tsconfig.json file, the code from one of the excluded files (subClassA.ts) is still being included in the compiled ...

The combination of React, Typescript, and MaterialUI Paper results in a stunning design with a sleek and

Whenever I include <Paper elevation={0} /> within my react component, I encounter the following issue: Cannot read properties of undefined (reading 'background') TypeError: Cannot read properties of undefined (reading 'background&apos ...

Vue version 3 is encountering an issue with a module that does not have an exported member in the specified path of "../../node_modules/vue/dist/vue"

After I updated my npm packages, errors started popping up in some of the imports from the 'vue' module: TS2305: Module '"../../node_modules/vue/dist/vue"' has no exported member 'X' The X instances affected inclu ...

Creating adaptable rows and columns with Angular Material's data table feature

My approach to rendering dynamic rows and columns using a basic table was successful: <tbody> <tr *ngFor="let row of data"> <td *ngFor="let val of row"> {{ val }} </td> </tr> </tbody> </ ...

How can eslint be used to enforce a particular named export?

Is there a way to use eslint to make it mandatory for JavaScript/TypeScript files to have a named export of a specific name? For instance, in the src/pages folder, I want all files to necessitate an export named config: Example of incorrect usage src/page ...

What is the best approach for filtering a nested array in this scenario?

Here is the response I am getting: let m = [ { name: 'Summary', subListExpanded: false, subList: [ ] }, { name: 'Upload', subListExpanded: false, subList: [ ...

Combine multiple objects to create a new object that represents the intersection of all properties

Imagine you have these three objects: const obj = { name: 'bob', }; const obj2 = { foo: 'bar', }; const obj3 = { fizz: 'buzz', }; A simple merge function has been written to combine these three objects into one: ...

The stacked bar chart in Apex is not displaying correctly on the x-axis

Currently, I am utilizing the Apex stacked bar chart within my Angular 16 project. In this scenario, there are 4 categories on the x-axis, but unfortunately, the bars are not aligning correctly with the x-axis labels. The data retrieved from my API is as ...

Implementing the ternary operator on a nested object field in typescript to enforce type validation

Is there an issue with my code or is this intentional? I want to write something similar to this. type MyDefinition = { salutation: string; value?: { typeOfValue: string; val?: string }; }; function create(name: string, input?: Partial<MyDefin ...

Typescript objects may contain keys that are dependent on certain parameters

I have a challenge with constructing an object that requires querying multiple database tables, resulting in a time-consuming process. To address this issue, clients of the object need to specify which specific parts they require. For example, let's c ...