Create an Object based on an Interface in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 10, 2022

banner

Photo from Unsplash

Create an Object based on an Interface in TypeScript #

To create an object based on an interface, declare the object's type to be the interface, e.g. const obj1: Employee = {}. The object has to conform to the property names and the type of the values in the interface, otherwise the type checker throws an error.

index.ts
interface Employee { salary: number; name: string; address: { country: string; city: string; }; } // ✅ Declare directly const obj1: Employee = { salary: 100, name: 'James', address: { country: 'Chile', city: 'Santiago', }, }; // ✅ Using type assertion const obj2 = {} as Employee; obj2.name = 'Carl'; obj2.salary = 200;

The first example in the code snippet declares the object to be of type Employee directly.

When using this approach, you have to declare the object to have all of the necessary properties of the interface.

You could use default values if you don't have all of the properties in advance:

index.ts
interface Employee { salary: number; name: string; address: { country: string; city: string; }; } // ✅ Declare directly const obj1: Employee = { salary: 0, name: '', address: { country: '', city: '', }, };

However, you can't omit any of the required properties that are defined on the interface.

The second example uses a type assertion to set the object's type to the type specified in the interface.

index.ts
interface Employee { salary: number; name: string; address: { country: string; city: string; }; } const obj2 = {} as Employee; // 👈️ type assertion obj2.name = 'Carl'; obj2.salary = 200;

Type assertions are used when we have information about the type of a value that TypeScript can't know about.

When using them, we effectively tell TypeScript that value X will be of type Y and not to worry about it. This could cause runtime errors if we are wrong.

In the example above, we tell TypeScript that the obj2 variable will be of type Employee, so it shouldn't worry about it.

However, note that we don't have to set all of the required properties on the object.

For example, the address property is required in the Employee interface, but we didn't get an error when we omitted it.

This is because when we used the as Employee syntax, we told TypeScript that the obj2 variable already has all of the properties an Employee has.

If you want to mark a property in an interface as optional, you can use a question mark.

index.ts
interface Employee { salary?: number; // 👈️ optional name?: string; // 👈️ optional address: { country: string; city: string; }; } const obj1: Employee = { address: { country: 'Chile', city: 'Santiago', }, };

When a property is marked as optional, we aren't required to set it when initializing the object of the specific type.

Optional properties can either be of the specified type or be undefined.

Even though TypeScript does not require us to set the salary and name properties when creating the object, it still checks that any properties added later on conform to the Employee interface.

An alternative way to create an object based on an interface is to define an initializer function.

index.ts
interface Employee { salary: number; name: string; address: { country: string; city: string; }; } function createEmployee(options?: Partial<Employee>): Employee { const defaults = { salary: 0, name: '', address: { country: '', city: '', }, }; return { ...defaults, ...options, }; } const obj2: Employee = createEmployee({ name: 'Alice' }); // 👇️ {salary: 0, name: 'Alice', address: {country: '', city: ''}} console.log(obj2);

The createEmployee function can be called with an options object or no parameters at all.

The function defines the default values for the Employee interface and uses the spread syntax (...) to unpack the defaults before unpacking any of the user provided values.

We used the Partial utility type to set all of the properties in the Employee interface to optional in the function's parameter.

Any of the values the function is passed, will override the default values.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.