Categories
TypeScript Answers

How to define a private property when implementing an interface in TypeScript?

Spread the love

Sometimes, we want to define a private property when implementing an interface in TypeScript.

In this article, we’ll look at how to define a private property when implementing an interface in TypeScript.

How to define a private property when implementing an interface in TypeScript?

To define a private property when implementing an interface in TypeScript, we can add private properties into the class that implements the interface.

For instance, we write

interface IModuleMenuItem {
  getName(): string;
}

class ModuleMenuItem implements IModuleMenuItem {
  private name;

  public getName() {
    return name;
  }

  protected setName(newName: string) {
    name = newName;
  }
}

to add the name private variable into the ModuleMenuItem class.

All interface properties must be public.

Conclusion

To define a private property when implementing an interface in TypeScript, we can add private properties into the class that implements the interface.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *