How to create a field inside a class in TypeScript?

April 17, 2022 - 2 min read

To create a field inside a class, you can use one of the following methods:

Create a field with a type

To create a field with the type you can first write the name of the field inside the class followed by the : symbol (colon) and then the type you need to use for the field.

It can be done like this,

// create a field inside
// class with `string` type
class Person {
  name: string; // <- this is a field with type
}

NOTE: By default, every field is public and is mutable if no modifiers are applied.

Create a field and initialize a value and let TypeScript infer the type

To create a field and initialize a value, you can write the name of the field inside the class followed by the = symbol (assignment operator), and then the value you need to initialize the field with. By doing so TypeScript will automatically infer the type based on the value that is assigned to the field.

It can be done like this,

// create a field inside
// class and initialize the value
class Person {
  name = "Anonymous"; // <- this is a field initialised with a `string` value
}

NOTE: By default, every field is public and is mutable if no modifiers are applied.

See the above codes live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.