Classes and Constructors

TypeScript classes compile to JavaScript class syntax according to the configured target. A constructor initializes an instance, and fields can be typed explicitly or inferred. implements checks that a class satisfies a contract; it does not add runtime methods or enforce the interface at runtime.

Use classes when identity, lifecycle, or encapsulated behavior is useful. For plain data transfer objects, interfaces and object literals are often simpler. Remember that class types and instance values are not the same thing: typeof SomeClass refers to the constructor side, while SomeClass in a type position generally describes instances.

A small class
interface Clock {
  now(): Date;
}

class SystemClock implements Clock {
  now(): Date {
    return new Date();
  }
}

const clock: Clock = new SystemClock();
💡 SystemClock satisfies the Clock contract because it has a compatible now method. The interface is a compile-time contract and does not exist as a runtime object.
Key Takeaways
  • Use classes for behavior and encapsulated state.
  • implements checks compatibility but adds no runtime behavior.
  • Distinguish instance types from constructor/static types.
Knowledge Check

Does `implements Clock` automatically generate missing methods?