Creating Objects from Interface in TypeScript

In TypeScript, interfaces are used as types and help in adding type safety to the existing variables, methods parameters, and return types. In contrast to other programming languages (such as Java), TypeScript allows to creation of objects that adhere to interface definitions, without requiring explicit class implementations.

This TypeScript tutorial discusses different ways to create an Object that conforms to the structure of a specified interface. For demo purposes, we are using the following Person interface which has only one field and one method.

interface Person {
  name: string;
  message(): string;
}
//1: Directly creating objects
const john: Person = {
  name: "John",
  message: () => {
    return "Hello, I am " + john.name;
  }
};

//2: From an existing object having similar structure
const newObject: Person = { ...existingObject };

//3: Creating a class implementing interface
class Employee implements Person { ...} 
const john = new Employee('John');

1. Initializing a New Object from the Interface

The simplest way to create a plain object that have the same properties and methods as available in the interface. As the interfaces do not exist in the runtime, ultimately we always have a simple object when the TypeScript is compiled into JavaScript.

const john: Person = {
  name: "John",
  message: () => {
    return "Hello, I am " + john.name;
  }
};

console.log(john);  // Output: "name": "John"
console.log(john.message());  // Output: "Hello, I am John" 

2. Copying an Existing Object into a New Object

Suppose we have an existing object that has similar properties and methods defined in the interface, then we can use the Object spread operation. The spread operator copies properties from an existing object to create a new object that matches the interface.

const existingObject = { name: 'Peter', message: () => { return "Hello, I am " + john.name; } };
const peter: Person = { ...existingObject };

console.log(peter);  // Output: "name": "Peter"
console.log(peter.message());  // Output: "Hello, I am Peter" 

Note that the existing object must have all the properties and methods specified in the interface. Existing objects can have additional fields and methods as well, but they cannot miss any field or method present in the interface. Even the method signatures must match.

For example, we can add the field ’email’ in the existing object and still, the object creation works.

const existingObject = { 
    name: 'Peter', 
    email: 'peter@gmail.com', 
    message: () => { return "Hello, I am " + john.name; } 
};
const peter: Person = { ...existingObject };  // Works !!

But if we just miss a simple thing, such as the method return type does not match, the compiler will throw the error:

const existingObject = { 
    name: 'Peter',  
    message: () => { /* return nothing. The return type is void. */ } 
};
const peter: Person = { ...existingObject }; // Error: The types returned by 'message()' are incompatible between these types

3. Implementing Interface into a Class

We can also implement the interface in a class and then create objects of that class. This provides additional type-safety options as well as we can define additional methods in the class. This can also help create objects that implement multiple interfaces.

In the following example, we have implemented the Person interface into Employee class. Now, we can create objects of the type Employee that conform to the structure of the Person interface as well.

class Employee implements Person {
    constructor(name: string) {
        this.name = name;
    }
    name: string;
    message(): string {
        return "Hello, I am " + this.name;
    };
    work(): string {		// New Method
        return this.name + ` is working`;
    }
}

const john = new Employee('John');
console.log(john.message()); // Output: Hello, I am John.
console.log(john.work()); // Output: John is working.

4. Conclusion

This typescript tutorial discussed the different ways to create objects from interfaces. It should be remembered that interfaces exist only in the compile time, in the source code, for type safety purposes. Interfaces do not exist in the runtime and that is why we cannot use the instanceof operator with interfaces.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode