Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 96 ยท Objects and Classes

Classes

Learn TypeScript classes - typed fields and methods, constructors, parameter properties, readonly fields, strictPropertyInitialization and the definite assignment operator.

TypeScript classes are JavaScript classes with types added. Everything you know about class, constructor, new, methods, extends and super still applies, and it all runs exactly as written. What TypeScript adds is a way to declare fields with types, check that every field is initialized, mark fields readonly, and a few conveniences such as parameter properties that remove boilerplate.

A class gives you two things at once: a value (the constructor function you call with new) and a type (the shape of the instances it creates). That double role is why classes feel natural in TypeScript, and why a class instance can be used anywhere its shape is expected, thanks to structural typing. This lesson covers the core of classes; the next ones add access modifiers and inheritance.

Fields, constructors and methods

In JavaScript you can create properties anywhere by assigning this.something = .... In TypeScript, every property must be declared in the class body with its type. The constructor then initializes it:

TypeScript A first typed class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Methods are typed like functions: parameter types are required, and return types are inferred (writing them, as here, documents the contract). Inside methods, this has the type of the class, so this.balance is a number and this.history a string[].

The class name is also a type. const a: BankAccount = account; works, and so does a function parameter of type BankAccount. Because typing is structural, a plain object with the same public properties and methods would also be accepted. Classes are not special in that sense.

Forgetting to declare a field is error TS2339, the same "property does not exist" error you get for objects:

TypeScript Undeclared fields (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The message is Property 'count' does not exist on type 'Counter'. Add count: number; (or count = 0;, which declares and initializes in one go, with the type inferred as number) to fix it.

strictPropertyInitialization

Strict mode includes strictPropertyInitialization. It requires every declared field to be initialized, either with an initializer in the class body or by an assignment in the constructor. Otherwise a field typed string would be undefined until someone sets it, and the type would lie.

TypeScript A field that is never initialized (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error is main.ts(3,3): error TS2564: Property 'bio' has no initializer and is not definitely assigned in the constructor. Without that check, the program would crash at runtime reading .length of undefined. There are four honest fixes, depending on what the field means:

  • Give it a default: bio = '';
  • Initialize it in the constructor, on every code path.
  • Make it optional: bio?: string; (its type becomes string | undefined, so readers must check).
  • Include undefined: bio: string | undefined;, the same idea when it must always be present.

TypeScript's analysis follows the constructor's control flow, so an assignment in only one branch of an if doesn't count. It does not look inside other methods you call from the constructor, which leads to the next feature.

Definite assignment: the ! modifier

Sometimes a field really is initialized before use, but TypeScript can't see it: a helper method sets it, a framework injects it, or an init() method must be called first. For those cases you can write ! after the field name, a definite assignment assertion:

TypeScript Definite assignment for a field set by a helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The ! switches off the initialization check for that one field; nothing changes at runtime. Like the non-null assertion, it's a promise you make, and if you're wrong you get undefined where the type says number. Prefer restructuring (here, computing the value in the constructor directly) when you can, and keep ! for cases where a framework or a lifecycle method really does the initialization.

The getter get fahrenheit() is an accessor: it's read like a property (t.fahrenheit, no parentheses) but computed on every read. Getters, setters and the accessor keyword are covered in Access Modifiers and Private Fields.

readonly fields

Mark a field readonly when it should never change after construction. It can be assigned in its declaration or in the constructor, and nowhere else:

TypeScript readonly fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

As with object types, readonly is shallow: items can't be replaced, but you can still push into it. Use readonly items: readonly string[] when the contents shouldn't change either. And it's compile-time only: at runtime it's a normal, writable property. (Readonly and Immutability goes deeper.)

The add method returns this, the polymorphic this type: it means "the type of the object the method was called on", which allows chaining like new Order('ord-7').add('book').add('pen') and keeps working in subclasses.

Parameter properties

Declaring a field, listing a constructor parameter and assigning one to the other is repetitive. TypeScript has a shorthand called parameter properties: put an access modifier (public, private, protected) or readonly in front of a constructor parameter, and it becomes a field automatically:

TypeScript Parameter properties remove boilerplate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Both classes produce identical objects. Parameter properties are popular in frameworks such as Angular and NestJS, where services receive their dependencies through the constructor.

They come with one caveat. Parameter properties are not just type annotations: TypeScript has to generate the this.sku = sku assignments, so the code can't be run by simply deleting the types. Node's built-in type stripping (node main.ts) and the erasableSyntaxOnly compiler option reject them, along with enum and namespace. If your project runs TypeScript that way, use the long form. Our editor compiles with the full compiler, so both work here. (See How TypeScript Works.)

Methods vs arrow function fields

Methods live on the prototype and get their this from how they're called. Pass a method around as a callback and this is lost, exactly as in plain JavaScript. An arrow function stored in a field captures this permanently:

TypeScript Losing this with a method callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript does not catch detached() by default, because a method's type doesn't record what this should be. You can opt in by declaring a this parameter, as shown in this, Parameter Destructuring and Type Predicates. The trade-off: arrow fields are created once per instance (more memory) and can't be overridden with super.method() calls in subclasses, while methods are shared on the prototype. Use methods by default and arrow fields for callbacks you hand to other code.

Class field semantics

With a modern target (ES2022 and later; our editor uses ES2024), TypeScript emits real JavaScript class fields. Field initializers run in declaration order before the constructor body, and parameter properties are assigned in the constructor body. So a field initializer can't use a parameter property:

TypeScript
class Rect {
  area = this.width * this.height; // error TS2729: Property 'width' is used before its initialization.
  constructor(public width: number, public height: number) {}
}

The same error appears when an initializer reads a field declared below it. Compute such values in the constructor, or use a getter (get area() { return this.width * this.height; }) so they're always current. Declaring a field without an initializer (name: string;) still creates the property, set to undefined, until the constructor assigns it. That's the useDefineForClassFields behavior, which is on by default for modern targets.

Static members, static blocks and singletons

Everything so far belongs to instances: each new BankAccount() gets its own balance. A static member belongs to the class itself and is reached through the class name. Use static members for things that exist once, such as a counter of how many instances were created, constants, and helper functions that don't need an instance. Access Modifiers shows static factories and caches; this section adds the patterns around them.

TypeScript Static fields, static methods and a static block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Static members are not available on instances (a.nextId is an error), and instance members can't be reached from static code without an object. Inside a static method, this is the class, so this.nextId works too, but writing the class name is clearer and survives being passed around as a plain function.

Static inheritance

Subclasses inherit the statics of their parent through the constructor's prototype chain. A subclass can read the parent's static values, add its own and call super methods. A mutable static field, however, is one shared slot unless the subclass redeclares it:

TypeScript Statics are inherited, and base constructors run first

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Two rules to remember about constructors: a derived class constructor must call super(...) before touching this (error TS17009 otherwise), and if the subclass declares parameter properties or initialized fields, super(...) must be the first statement. If a subclass doesn't define a constructor, TypeScript passes all arguments to the base constructor for you.

Utility "static classes"

Some languages require every function to live in a class, and developers coming from them write classes full of static methods:

TypeScript
class StringUtils {
  static capitalize(text: string): string {
    return text.charAt(0).toUpperCase() + text.slice(1);
  }
  static isBlank(text: string): boolean {
    return text.trim() === '';
  }
}

TypeScript has no static class keyword, and you rarely need one. A module with exported functions does the same job, tree-shakes better and is easier to test:

TypeScript
// string-utils.ts
export function capitalize(text: string): string {
  return text.charAt(0).toUpperCase() + text.slice(1);
}
export function isBlank(text: string): boolean {
  return text.trim() === '';
}

Use static members when they truly belong to a class: factories (Money.fromCents), constants tied to the type, and caches. If you want to stop anyone from instantiating a utility class, give it a private constructor() {}.

The singleton pattern

A singleton is a class that should have exactly one instance, such as a configuration store. The classic recipe is a private constructor plus a static accessor that creates the instance lazily:

TypeScript A lazy singleton with a private constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The constructor runs once, on first access. The private constructor blocks new Settings() from outside, while static #instance keeps the cache truly private at runtime.

In many programs a module-level constant is a simpler singleton. ES modules are evaluated once and cached, so every importer shares the same object:

TypeScript
// settings.ts
export const settings = new Map<string, string>();

Reach for a class-based singleton when you need lazy creation or to hide the constructor. Be aware that singletons are global state: they make tests harder, because one test's changes leak into the next. Passing the object in as a constructor argument is often a better design.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Under strict mode, does this compile? class A { name: string; constructor() {} }

    strictPropertyInitialization requires every field to be initialized in its declaration or in the constructor.
  2. 2. What does constructor(private readonly id: string) {} do?

    That's a parameter property: the modifier turns the parameter into a field and TypeScript generates the assignment.
  3. 3. What does celsius!: number; change at runtime?

    The definite assignment assertion is a compile-time promise. If the promise is wrong, the field is simply undefined.
  4. 4. class T { readonly tags: string[] = []; } Which line compiles for const t = new T()?

    readonly prevents reassigning the property, but it's shallow, so the array can still be mutated.
  5. 5. Why might node main.ts (type stripping) refuse a class with parameter properties?

    Type stripping only removes type syntax. Parameter properties require emitting this.x = x assignments, like enum and namespace.

Summary

  • A class is both a value (the constructor) and a type (the instance shape); instances are checked structurally like any object.
  • Declare every field with its type; initialize it in the declaration or the constructor. strictPropertyInitialization (TS2564) enforces this.
  • Fix uninitialized fields with a default, a constructor assignment, ? or | undefined. Use the ! definite assignment assertion only when something TypeScript can't see initializes the field.
  • readonly fields can only be set in their declaration or the constructor; they're shallow and compile-time only.
  • Parameter properties (constructor(public name: string)) declare and assign fields in one step, but aren't erasable syntax.
  • static members live on the class: counters, constants, factories and static { } setup blocks. They're inherited by subclasses, and derived constructors must call super(...) before using this.
  • Prefer module functions over classes full of static methods; use a private constructor with a static accessor for a lazy singleton, or a module-level constant for a simple one.
  • Methods lose this when detached; arrow function fields keep it at the cost of one function per instance.

Next: Access Modifiers and Private Fields