Diego Lope Loyola
Diego Lope Loyola

Reputation: 1061

What is the naming convention for interfaces and classes in TypeScript?

I have the following:

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('[email protected]', 'foobar')
}

I have to put the letter "I" before the interface name, is that correct or should I do it differently?

Upvotes: 42

Views: 65889

Answers (3)

Shravan Dhar
Shravan Dhar

Reputation: 1560

The answers are opinionated for this. Microsoft's convention here But following is the general norm:

  1. Classes are generally noun, written in PascalCase
  2. Interface is also PascalCase (prefixing 'I' is not recommended)
  3. Enums and it's fields are both written in PascalCase
  4. variables (let/const) are written in camelCase. Sometimes const are also written in UPPERCASE.

Upvotes: 3

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221282

There's no official naming convention though it's common in the broader TS community to not use I for interfaces unless they're explicitly for being implemented by classes like:

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;
  }
}

(Pattern adapted from sveltekit-starter by Navneet Sharma.)

So which naming method you choose for interfaces is ultimately at your own discretion.

Upvotes: 19

DeborahK
DeborahK

Reputation: 60578

Someone has developed a TypeScript style guide. You can find it here: https://ts.dev/style

From that guide:

This is the style guide for the TypeScript language that was based on the one that is provided by Google. It contains both rules and best practices. Choose those that work best for your team.

This is what it says about interface naming:

Do not mark interfaces specially ( IMyInterface or MyFooInterface) unless it's idiomatic in its environment. When introducing an interface for a class, give it a name that expresses why the interface exists in the first place (e.g. class TodoItem and interface TodoItemStorage if the interface expresses the format used for storage/serialization in JSON).

Upvotes: 27

Related Questions