How can I create an object based on an interface file definition in TypeScript?
You simply import the interface from its definition file, and then use that interface as a type annotation when creating an object (or class) that must adhere to the interface’s shape. This ensures that TypeScript enforces all properties and types from the interface.
1. Define (or Import) Your Interface
Let’s say you have a separate file, types.d.ts
or myInterface.ts
, containing:
export interface MyInterface { id: number; name: string; isActive?: boolean; // optional property }
2. Create an Object that Matches the Interface
In another file, import the interface and then create an object that implements its structure:
import { MyInterface } from "./myInterface"; const myObj: MyInterface = { id: 123, name: "Alice", // isActive is optional };
- Here,
myObj
must have at leastid
(number) andname
(string). - If you include
isActive
, it has to be a boolean.
3. Rely on TypeScript’s Checks
If you try to assign incorrect types or miss required properties, TypeScript will give you a compile-time error:
const badObj: MyInterface = { // Error: Property 'id' is missing name: "Bob" };
This ensures your objects conform to the interface definition.
4. Using a Class that Implements the Interface
Alternatively, you could define a class that implements the interface:
import { MyInterface } from "./myInterface"; class MyClass implements MyInterface { id: number; name: string; isActive?: boolean; constructor(id: number, name: string, isActive?: boolean) { this.id = id; this.name = name; this.isActive = isActive; } }
Then create an instance:
const objInstance = new MyClass(456, "Charlie", true);
This is another route if you want additional methods or class-level logic.
5. Summary
- Import (or define) your interface from its
.ts
file. - Annotate your object (or class) with
: MyInterface
. - Fulfill all required properties (and types).
- TypeScript will enforce correctness at compile time.
If you want to master the JavaScript fundamentals behind TypeScript’s type system, check out the Grokking JavaScript Fundamentals course by DesignGurus.io. It covers crucial concepts like closures, prototypes, and async patterns—helping you write more robust and maintainable TypeScript code.