Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

what is an interface typescript

/*
In TypeScript, you can create your OWN types and use them the 
same way that you would primitive types like numbers and strings.

One way to do this is by creating an interface. 
An interface in TypeScript is a data structure that defines the shape of data.
Let’s see this in action:
*/

interface Order {
  customerName: string,
  itemNumbers: number[],
  isComplete: boolean
}

/*
The interface keyword is used to initialize an interface,
which shows us the SHAPE of the data that’s coming. 
Think of an interface like a factory mold. 
This interface is used to stamp out Order types for a store. 
Now let’s actually use the Order interface to type a variable:
*/

let order1: Order;
order1 = {
  customerName: "Abiye",
  itemNumbers: [123,44,232],
  isComplete: false
}

/*
Let’s analyze the order1 variable. 
It is of an "Order" type, so it must have 3 fields: 
the first field is a string, the second field is an array of integers, 
and the third field is a boolean. It MUST have each of those fields in order to 
fulfill the contract of the interface. Try omitting one of the fields in 
order1 (for example, remove the customerName). 
You will receive an error because the contract has not been fulfilled.
*/

/*
An interface contract is simply the list of fields in that interface
that any variable needs if it wants to use that type. 
All of the normal fields within an interface must be implemented in any 
variable that uses that type.
/*
 
PREVIOUS NEXT
Tagged: #interface #typescript
ADD COMMENT
Topic
Name
6+7 =