How to Create an Object from an Interface in TypeScript?

In this tutorial, I will explain how to create an object from an interface in TypeScript. By the end of this article, you will have a solid understanding of how to define and use interfaces to create objects that are type-safe and maintainable.

TypeScript Interfaces

TypeScript interfaces allow you to define the shape of an object. They provide a way to describe the structure of an object, which includes the types of its properties. This ensures that the objects you create conform to a specific structure, making your code more predictable and easier to debug.

Define an Interface in TypeScript

Let’s start by defining a simple interface. Suppose we are working on a project management application for a company based in New York. We want to define the structure of a Project object.

interface Project {
    id: number;
    name: string;
    startDate: Date;
    endDate: Date;
    budget: number;
    clientName: string;
}

Read Choose Between TypeScript Classes and Interfaces

Create an Object from an Interface

Once we have defined the Project interface, we can create an object that adheres to this structure. Here’s how you can do it:

const newProject: Project = {
    id: 1,
    name: "Website Redesign",
    startDate: new Date("2024-01-15"),
    endDate: new Date("2024-06-15"),
    budget: 50000,
    clientName: "Tech Innovators Inc."
};

In this example, we create a newProject object that matches the Project interface. This ensures that all required properties are present and have the correct types.

Read Convert JSON to TypeScript Interface

Using Interfaces with Functions

Interfaces can also be used to type-check the parameters of functions. This is particularly useful in large applications where functions may be called from various parts of the codebase.

function displayProjectDetails(project: Project): void {
    console.log(`Project Name: ${project.name}`);
    console.log(`Client: ${project.clientName}`);
    console.log(`Budget: $${project.budget}`);
    console.log(`Timeline: ${project.startDate.toDateString()} to ${project.endDate.toDateString()}`);
}

displayProjectDetails(newProject);

In this function, displayProjectDetails, we ensure that the project parameter conforms to the Project interface. This provides type safety and helps prevent runtime errors.

Here is the complete code, that I executed using VS code.

interface Project {
    id: number;
    name: string;
    startDate: Date;
    endDate: Date;
    budget: number;
    clientName: string;
}
function displayProjectDetails(project: Project): void {
    console.log(`Project Name: ${project.name}`);
    console.log(`Client: ${project.clientName}`);
    console.log(`Budget: $${project.budget}`);
    console.log(`Timeline: ${project.startDate.toDateString()} to ${project.endDate.toDateString()}`);
}
const newProject: Project = {
    id: 1,
    name: "Website Redesign",
    startDate: new Date("2024-01-15"),
    endDate: new Date("2024-06-15"),
    budget: 50000,
    clientName: "Tech Innovators Inc."
};

displayProjectDetails(newProject);

Here is the exact output in the screenshot below:

Create an Object from an Interface in TypeScript

Read Set Default Values in TypeScript Interfaces

TypeScript Interfaces Optional Properties and Readonly

TypeScript interfaces also support optional properties and readonly properties. Optional properties are useful when some properties might not be present in every object. Readonly properties ensure that certain properties cannot be modified after the object is created.

interface Project {
    id: number;
    name: string;
    startDate: Date;
    endDate: Date;
    budget: number;
    clientName: string;
    description?: string; // Optional property
    readonly createdBy: string; // Readonly property
}

const anotherProject: Project = {
    id: 2,
    name: "Mobile App Development",
    startDate: new Date("2024-02-01"),
    endDate: new Date("2024-08-01"),
    budget: 75000,
    clientName: "Startup XYZ",
    createdBy: "John Doe"
};

// anotherProject.createdBy = "Jane Smith"; // This will cause a compile-time error

In this updated Project interface, description is an optional property, and createdBy is a readonly property. This allows for more flexible and secure object definitions.

Conclusion

In this tutorial, I explained how to create an object from an interface in TypeScript with some real examples. Do let me know in the comment below if you still have some questions.

You may also like: