Profile ImageDaniel Bischoff
tagged in TypeScript • Mar 28, 20181 min read

How to create an interface from an object

In this article I want to show you, how you can let TypeScript dynamically create an interface from an object. You need to do this, when you want to pass your object as a function parameter because TypeScript expects that you define a type for this parameter.

const myObject = {
  prop1: 'value1',
  prop2: 'value1',
};

const doSomething = (myObject: ??) => {
//...
}

So you want the method's parameter myObject to have the shape of the variable myObject. The most obvious way would be to create an interface that has this shape.

const myObject = {
  prop1: 'value1',
  prop2: 'value1',
};

interface MyObject {
  prop1: string;
  prop2: string;
}

const doSomething = (myObject: MyObject) => {
//...
}

But the downside of this approach is, that we have to update the interface everytime we change the properties of the variable myObject. The most elegant way would be to let TypeScript create an interface for us.

And luckily, TypeScript can do this!

const myObject = {
  prop1: 'value1',
  prop2: 'value1',
};

type MyObject = typeof myObject;

const doSomething = (myObject: MyObject) => {
//...
}

The only thing we have to do is to declare a new type MyObject and tell TypeScript to assign the type of the variable myObject to it. Now everytime we change the properties of the variable myObject, TypeScript will automatically update the shape of the MyObject type.

Liked the article? Share it!

Tweet