TypeScript Interface and Class Key Properties Tutorial with examples

This tutorial explores the keys of an interface or class in TypeScript.

Let’s Understanding Key Properties

In TypeScript, key properties refer to the fields or properties defined within an interface or class. Interfaces serve as compile-time constants and are not available at runtime, whereas classes operate at runtime.

Typescript get Key properties of an class

For example, an class contains different fields and properties

class Employee {
    readonly id?: number,
    readonly name?: string,
    readonly title?: string,
    readonly isActive?: boolean,
  ) {}

The class encapsulates keys initialized within its constructor.

Creating an object of this class yields the following structure:

 Employee: {
  "id": undefined,
  "name": undefined,
  "title": undefined,
  "isActive": undefined

Using Object.keys method allows us to obtain an array of properties or fields.

const keys: string[] = Object.keys(new Employee());


["id", "name", "title", "isActive"]

Typescript get Key properties of an Interface

For example, an interface representing an employee:

export class Employee {
  id: number;
  title: string;
  name: string;
  salary: number;
  isActive: boolean;

In this case, the key properties are directly listed within the interface definition.