Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 96 ยท Objects and Classes

Classes, Interfaces and Structural Typing

Learn how TypeScript classes work with interfaces - implements, instance types vs typeof Class, constructor types like new () => T, abstract constructors and mixins.

A TypeScript class is two things at once. It's a value: a constructor function that exists at runtime and that you call with new. And it's a type: the shape of the objects it creates. Most of the confusion around classes and interfaces comes from mixing those two up, so this lesson pulls them apart carefully.

You'll learn what implements really checks (and what it doesn't), why a plain object can stand in for a class instance, how typeof SomeClass differs from SomeClass, how to write constructor types such as new () => T for factories and plugin registries, and how to build mixins that add behavior to any class. It builds on Classes, Access Modifiers and Private Fields and Inheritance and Abstract Classes.

implements: a promise the compiler checks

An interface describes a shape. When a class says implements SomeInterface, it promises that its instances will have that shape, and TypeScript checks the promise right at the class declaration. A class can implement several interfaces at once, separated by commas:

TypeScript A class that implements two interfaces

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.

Circle promises both shapes, Rectangle only one. The array is typed as Shape[], so the loop can call name and area() on every element without knowing which class it came from. That's the everyday reason to use implements: code that consumes shapes depends on the interface, not on a concrete class.

If a class breaks its promise, the error points at the class, not at some distant call site where the object is used. Here the class forgets area() and spells describe with the wrong return type:

TypeScript Breaking the implements promise (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 run stops with two errors and prints nothing else:

TEXT
main.ts(10,7): error TS2420: Class 'Square' incorrectly implements interface 'Shape'.
  Property 'area' is missing in type 'Square' but required in type 'Shape'.
main.ts(16,3): error TS2416: Property 'describe' in type 'Label' is not assignable to the same property in base type 'Printable'.
  Type '() => number' is not assignable to type '() => string'.
    Type 'number' is not assignable to type 'string'.

TS2420 is the "you promised a member you don't have" error; TS2416 means a member exists but has an incompatible type. The indented lines underneath explain the reason step by step, from the outside in.

What implements does not do

implements is only a check. It doesn't add members to the class, it doesn't copy default values, and, the one that surprises people, it doesn't give types to method parameters. You still annotate every parameter yourself:

TypeScript implements does not type your parameters (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.

TEXT
main.ts(6,11): error TS7006: Parameter 'input' implicitly has an 'any' type.

You might expect input to pick up string from the interface, but it doesn't: the class is checked against the interface after its own types are worked out. The fix is to write isValid(input: string). Also note that the class may have more members than the interface demands, and an optional interface property isn't created on the class just because you implemented the interface.

Structural typing applies to classes too

TypeScript compares types by their structure, not by their names. A class instance type is just an object type with the class's public members, so any object with the same members fits, whether it came from that class or not:

TypeScript Plain objects can stand in for class instances

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 output ends with false and then 3 Pixel. The type system was satisfied by the shape, but at runtime fake has no link to Point.prototype, and p is really a Pixel. So if your code relies on instanceof, a prototype method that isn't part of the type, or the class's constructor running, a lookalike object will slip through. The deeper rules behind this are the topic of the next lesson, Type Compatibility and Variance.

private and protected members make a class nominal

There's one exception. If a class has a private or protected member, only instances of that class (or its subclasses) are compatible with it, because a lookalike can't have that private member. The same holds for JavaScript #private fields:

TypeScript A private member blocks lookalikes (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.

TEXT
main.ts(16,22): error TS2345: Argument of type 'OrderId' is not assignable to parameter of type 'UserId'.
  Types have separate declarations of a private property 'brand'.
main.ts(17,22): error TS2741: Property 'brand' is missing in type '{ value: number; }' but required in type 'UserId'.

Delete the last two calls and the program runs. This is a handy trick for IDs and units that must never be mixed up; the next lesson shows a lighter-weight version called a branded type.

The instance type vs typeof Class

When you write Point in a type position, you mean the instance type: what new Point(...) returns. To talk about the class itself, the constructor function with its static members, you use typeof Point:

TypeScript Point versus typeof Point

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.

today.unit would be an error, because statics live on the constructor, not on instances. typeof Temperature includes unit, count, fromFahrenheit and the ability to be called with new. The built-in utility type InstanceType<T> goes the other way; keyof, typeof and Indexed Access Types covers typeof in types in general.

Interfaces can't describe static members of a class. implements only checks the instance side. If you need to require statics, type the constructor itself, for example const Plugin: PluginClass = MyPlugin; where PluginClass is an interface with a construct signature and static properties.

Constructor types: new () => T

A constructor type describes something you can call with new. The syntax mirrors a function type with new in front: new (name: string) => Animal. They're how you write factories, dependency containers and plugin registries that receive classes instead of instances:

TypeScript Factories and registries with constructor types

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.

create is a tiny generic function: TypeScript infers T from the class you pass, so u is typed as Upper. You can also write constructor types as a construct signature inside an object type, { new (): Plugin }, which is the form to use when the type also needs static properties.

Abstract constructor types

An abstract class can't be passed where new () => T is expected, because you can't call new on it. If a function only needs the class for instanceof checks or prototype access, accept an abstract constructor type, which matches both abstract and concrete classes:

TypeScript abstract new () => T

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 parameter list (...args: never[]) means "any constructor parameters at all", because every parameter type accepts never. It's a strict-mode-friendly way to avoid any when you don't care about the arguments.

Mixins: classes built by functions

JavaScript classes can extend any expression that produces a constructor, including a function call. A mixin is a function that takes a class and returns a new class extending it with extra members. TypeScript understands this pattern and merges the types:

TypeScript Composing classes with mixins

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.

note has id, text, tags and tag(), all fully typed, and tag() returns this, so calls chain. Shouting constrains its base with Constructor<{ text: string }>, so applying it to a class without a text property is a compile error. (You'll meet extends constraints properly in Generic Constraints and Defaults.)

The any[] in Constructor isn't a style slip: TypeScript's mixin rule demands a constructor with a single rest parameter of type any[]. Keep it in that one alias and nowhere else. Mixins are powerful but harder to read than plain composition (an object that holds a helper), so prefer composition unless you really need the members on the class itself.

Interface or abstract class?

Both describe a contract, but they live in different worlds:

Interface Abstract class
Exists at runtime No (erased) Yes
Can hold code and fields No Yes
A class can use several Yes (implements A, B) No (single extends)
Works with instanceof No Yes
Works for plain objects Yes Only structurally

A good default is: interfaces for contracts that callers depend on, abstract classes when subclasses should share real implementation. Many codebases combine them, an abstract class that implements an interface.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class Report implements Printable but has no print() method that Printable requires. What happens?

    implements is checked at the class itself. A missing member is reported as TS2420, Class 'Report' incorrectly implements interface 'Printable'.
  2. 2. Given class Box { constructor(public size: number) {} }, does const b: Box = { size: 3 }; compile?

    Class instance types are structural. Any object with the same public members fits, but at runtime it is still a plain object, so instanceof Box is false.
  3. 3. What is the difference between the types Temperature and typeof Temperature?

    In a type position the class name means the instance type. typeof Temperature describes the constructor function itself, including static members.
  4. 4. Why can't you pass an abstract class to a parameter of type new () => T?

    Use an abstract constructor type such as abstract new () => T when you only need instanceof or prototype access; it accepts abstract and concrete classes.
  5. 5. Two classes have identical public members, but each declares private brand: string. Are their instances assignable to each other?

    TypeScript reports that the types have separate declarations of a private property, so the classes behave nominally.

Summary

  • A class is both a value (the constructor) and a type (the instance shape). In type positions, Point means the instance type and typeof Point the constructor type.
  • implements checks the class against one or more interfaces at the declaration (TS2420, TS2416). It doesn't add members or type method parameters.
  • Class instance types are structural: lookalike objects fit, but instanceof and prototype behavior differ at runtime. private, protected and #private members make a class nominal.
  • Constructor types (new (...) => T, { new (): T }) let you pass classes to factories and registries; abstract new (...) => T also accepts abstract classes. InstanceType<typeof C> recovers the instance type.
  • Mixins are functions that return a class extending their argument; the base constructor type must use ...args: any[]. Prefer composition when it's enough.

Next: Type Compatibility and Variance