Typescript get Keys of an class and interface with examples

This tutorials explains about keys of an Interface or class in Typescript

This tutorial explains about output array of properties of an interface or class.

Interface are compile time constants, not avialiable at runtime. Class are 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
    ) {}

Clss contains keys, initialized in a constructor.

Create an object of an class prints the following object

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

use Object.keys method returns an array of properties or fields.

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



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

Typescript get Key properties of an Interface

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