how to create an interface in typescript

To create an interface in TypeScript, you first need to define the shape of the object you want to create. This can be done by using the interface keyword, followed by the name of your interface and curly braces containing the properties of your object along with their data types. For example:

index.ts
interface MyObject {
  name: string;
  age: number;
  isStudent: boolean;
  hobbies: string[];
}
97 chars
7 lines

Here, we have created an interface called MyObject with four properties: name, age, isStudent, and hobbies. The name property is of type string, the age property is of type number, the isStudent property is of type boolean, and the hobbies property is an array of strings.

Once you have defined your interface, you can use it to create objects that conform to its shape. For example:

index.ts
const person: MyObject = {
  name: "John",
  age: 25,
  isStudent: true,
  hobbies: ["reading", "hiking", "coding"]
}
118 chars
7 lines

Here, we have created an object called person that conforms to the shape of the MyObject interface by including all the required properties with their correct data types.

Using interfaces in TypeScript can help you write clearer and more maintainable code by enforcing a consistent structure for your objects throughout your program.

gistlibby LogSnag