How to create fields that can be accessed without creating an instance of the class in TypeScript?

Published April 28, 2022

To create fields in class that can be accessed without creating an instance of the class, you need to define the field as a static member of the class in TypeScript. To create a static member you need to write the keyword static followed by the member name and the value you need to assign to the field/member.

TL;DR

// a simple class with 2 fields,
// a constructor and a `static` field
class Person {
  name: string;
  age: number;

  // this is the static field in class
  static className = "Person";

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

// access the `static` member `className`
// without creating an instance of the `Person` class
console.log(Person.className); // Person ✅

For example, let's say we have a class called Person with 2 fields called name and age, a constructor like this,

// a simple class with 2 fields
// and a constructor
class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

Now the 2 fields, name and age can only be accessed when you create an instance of the class.

But we need to just attach it to the class itself and be able to access that field/member without creating an instance of the Person class. To do that we need to use the static keyword inside the class followed by writing the field name and then assigning a value to it.

Let's make a static field called className and assign the value of Person to it.

It can be done like this,

// a simple class with 2 fields,
// a constructor and a `static` field
class Person {
  name: string;
  age: number;

  // this is the static field in class
  static className = "Person";

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

Now that we have created the static field, let's access the className static field without creating an instance of the class.

It can be done like this,

// a simple class with 2 fields,
// a constructor and a `static` field
class Person {
  name: string;
  age: number;

  // this is the static field in class
  static className = "Person";

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

// access the `static` member `className`
// without creating an instance of the `Person` class
console.log(Person.className); // Person ✅

As you can see that we were able to access the className static field in the Person class and the output of Person is logged to the console.

We have successfully created a class member that can be accessed without creating a class instance. Yay 🥳!

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter