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.ts97 chars7 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.ts118 chars7 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