Writing a constructor in TypeScript
Tags: typescript
Published: 2022-01-21 17:25:25

**Written by [Kealan Parr](https://blog.logrocket.com/author/kealanparr/)✏️**

Any mature TypeScript codebase will typically make heavy use of interfaces.

They are, after all, the building blocks of adding static compile-time checks on your code, and they ensure you are sensibly using the collective/custom types you define within your code.

Interface syntax is simple, and interfaces offer a [host of advantages](https://www.executeprogram.com/courses/everyday-typescript/lessons/interfaces) when used in your code, such as:

*   Produce simple, easily understood error messages
*   Sometimes compile faster than `type` definitions
*   Used heavily by the TypeScript community, so they are a common best practice, (the TypeScript documentation utilizes them heavily also)
*   The [TypeScript team endorses interfaces](https://twitter.com/drosenwasser/status/1319205169918144513), too. Daniel Rosenwasser, TypeScript's program manager, has endorsed interfaces over `type`

## Constructing interfaces

Sometimes, as part of a design pattern or for certain use-cases, developers may want to specifically create an instance variable from an interface.

A simple example of an interface we might want to construct could be:

```ts
interface Animal {
  numLegs: number,
  wings: boolean
}
```

But how we add a constructor to this type is not clear.

Even more confusingly, in the compiled JavaScript, the interface won’t even exist. It only exists to check our types and then will be [totally removed](https://www.typescriptlang.org/play?#code/LAKAlgdgLgpgTgMwIYGMYAICCEwFskA26A3qOuhAK64AyMA5gM4BcF1ARvADRnoDukejAAmrdgHtxBGEgigAvqFCRYiVBgAS1WSV5I4uFm1yc4PEOWlNWVE915gAjjY7wFQA), thanks to a process called type erasure.

So, let’s start with a [failing example](https://www.typescriptlang.org/play?ssl=13&ssc=2&pln=1&pc=1#code/JYOwLgpgTgZghgYwgAgJLmvJB1YYAWAwgPYgDOYArlAmMVMgN4CwAUMh8gqTMAOYAuZBSig+AbjacupEZVr0AFNxC9BwsKJB8AlEMYzV-ISLHIAvpNbm2bBABs4ZMshJG+hR8+TAAtgAd7CF8IcBd0SFhECFwCNwpqBQYWdmQpZH9KACN7YARDNWQAXmQAclKrdJU5JOUeYw0tXSZ0jgJgMgA6FUKSnv4rDhtrIA) and solve it iteratively:

```ts
interface InterfaceWithConsturctor {
  config: string;
  constructor(config: string): { config: string };
}

class ConfigClass implements InterfaceWithConsturctor {

  public config = '';

  constructor(config: string) {
    this.config = config;
  }
}
```

The error we are currently facing is:

```ts
- Class 'ConfigClass' incorrectly implements interface 'InterfaceWithConsturctor'.
- Types of property 'constructor' are incompatible.
- Type 'Function' is not assignable to type '(config: string) => { config: string; }'.
- Type 'Function' provides no match for the signature '(config: string): { config: string; }'.
```

Even though our two constructors match (in the interface versus in the class implementing the interface), it throws an error and won’t compile.

You can see in the two code examples that they are using the same type, and, by the looks of it, should compile just fine.

## Adding a constructor to a TypeScript interface

The [docs](https://www.typescriptlang.org/docs/handbook/interfaces.html#difference-between-the-static-and-instance-sides-of-classes) include an example covering this exact scenario.

Our earlier examples are failing because, according to the docs, “when a class implements an interface, only the instance side of the class is checked. Because the constructor sits in the static side, it is not included in this check.”

This reads weirdly, but it essentially means that [the constructor isn’t an instance type method](https://www.typescriptlang.org/docs/handbook/interfaces.html#difference-between-the-static-and-instance-sides-of-classes).

By instance type method, we’re referring to a “normal” function that would be called with `obj.funcCall()` existing on the object instance, as a result of using the `new` keyword. The constructor actually belongs to the static type.

In this case, the static type means the type it belongs to, without instantiating it, e.g., `InterfaceWithConsturctor`.

To fix this, we need to create two interfaces: one for the static type methods/properties and one for the instance type methods.

Our [new working](https://www.typescriptlang.org/play?ssl=7&ssc=2&pln=1&pc=1#code/JYOwLgpgTgZghgYwgAgMIHsQ2AcwJLjTxLIDeAsAFDLIKbY4BcyAzmFKDgNxUC+VVUJFiIUBYcQgB1YGAAWGEGwCuUBGHRQyVGiAgB3ABQhmbDiBwBKZqVr1cp9p2S8elfpSoIANnBYs0exxkYABbAAdvCFCIcADFBnEiUW1PamRw5QAjb2AEOywHVicLNx0Cs2V1TWRDOkKmYvMrVJoaeWAWADp6hmQAXgKGNxoPDyoYZRB1YExWCDAAFTkIAGUwOEhjZiSRJBl5RRU1DShLVuQoBdUQZD19O8MAcls2TYgbWlyEAGsIABNmOxlBAADQZVQIOR+AF4SChFhAqAglwuJ6WNzjSj1FjoKJdbzoHCGFgLZZrDZbBK4Sw9IIYoA) example, [inspired](https://stackoverflow.com/questions/13407036/how-does-interfaces-with-construct-signatures-work) by the [engineering lead of TypeScript](https://twitter.com/searyanc), looks like this.

```ts
interface ConfigInterface {
  config: string;
}
interface InterfaceWithConsturctor {
  new(n: string): { config: string };
}
class Config implements ConfigInterface {
  public config: string;
  constructor (config: string) {
    this.config = config;
  }
}
function setTheState(n: InterfaceWithConsturctor) {
  return new n('{ state: { clicked: true, purchasedItems: true } }');
}
console.log(setTheState(Config).config);
```

This now logs as `{ state: { clicked: true, purchasedItems: true } }`.

## Benefits to using TypeScript interface constructors

By using this language feature, you can create more composable objects that don’t rely on inheritance to share code.

With a constructor on the interface, you can specify that all of your types must have certain methods/properties (normal interface compliance) but also control how the types get constructed by typing the interface like you would with any other method/property.

We are [relying on abstractions rather than concretions](https://softwareengineering.stackexchange.com/questions/401769/depend-on-abstractions-not-on-concretions-what-is-the-exact-meaning-of-this-t). There’s [an example](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgMIBsD2CDWrMgDOYUArgmJlMgN4BQyyIEA7sgBQAWmpUAXE1IBbAEbQANMiGhSkASGFioASgEZsOAJLho8JAG46AXzp1QkWIhTrc2i3pT1GYYLnarkAN0zAAJoZM6GFIQCmACZAQoCDhIGxx2BkjKfjQsXHwiEnIU8STuXnlFCSTpBTlBUWg6D3i7XStaJOiwXhAmVmSqLh4oSTLZCGUA0wR0OEJCZAARYABzYDA4dHjkYCEAB3QIIQhwKbqdSyQmxgQCYjIKbs4iqr6pO6VlWhNnVwSXp0ZIi8xtgB0WDm7AARGIIBtkBCNqDhkkTIExhMpgBBEDLTBzVbrLY7PZgA7pLRHBynX5ZK4pLhPCSPSrPV5JFxuL5JM5-QHAsEsnDISi4OGGRiI0zbMDIXzzRbLZAAXki0ViEHi7FmCyWK2JkgAjAAmXUAdnh4uQcAxwPlipicWJ7HRmOx2uQhskAGY9cMgA) from the old [TypeScript docs](https://www.typescriptlang.org/docs/handbook/interfaces.html#difference-between-the-static-and-instance-sides-of-classes) to highlight this.

The old docs are still valid TypeScript, and they’re a really clear example of what we’re discussing - so I have kept the legacy URL for clarity.

```ts
//
// Instance and static interfaces
//
interface ClockConstructor {
  new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
  tick(): void;
}

function createClock(
  ctor: ClockConstructor,
  hour: number,
  minute: number
): ClockInterface {
  return new ctor(hour, minute);
}

//
// Clock implementation classes
//
class DigitalClock implements ClockInterface {
  constructor(h: number, m: number) {}
  tick() {
    console.log("beep beep");
  }
}
class AnalogClock implements ClockInterface {
  constructor(h: number, m: number) {}
  tick() {
    console.log("tick tock");
  }
}

// Now we allow relatively generic (but typed!) creation of Clock classes
let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);
```

Here, we are creating a strictly typed constructor function with the arguments we need other classes to use, but at the same time, allowing it to be generic enough it fits multiple use-cases.

It also ensures we are keeping [low coupling, high cohesion](https://stackoverflow.com/questions/14000762/what-does-low-in-coupling-and-high-in-cohesion-mean) in our code.

## Conclusion

I hope this has explained not only how to add a constructor onto an interface, but some of the common use-cases for when and why it might be done, as well as the syntax of how you can achieve it.

It is a common enough occurrence that the docs even explain the basic approach, and it is useful to understand the two sides of static versus instance scope in the underlying JavaScript/TypeScript world.

---

## Writing a lot of TypeScript? [Watch the recording](https://blog.logrocket.com/typescript-meetup-recap/?utm_source=social&utm_medium=organic&utm_campaign=21Q3_WB_TS-Tech-Meetup0930#utm_source=social&utm_medium=organic&utm_campaign=21Q3_WB_TS-Tech-Meetup0930) of our recent TypeScript meetup to learn about writing more readable code.

![alt text](https://blog.logrocket.com/wp-content/uploads/2021/07/typescript-4-4-more-readable-code.png)

TypeScript brings type safety to JavaScript. There can be a tension between type safety and readable code. Watch the recording for a deep dive on some new features of TypeScript 4.4.