This is the 11th day of my participation in the Novembermore Challenge

Implement interfaces in TypeScript

JavaScript doesn’t support interfaces, but that doesn’t mean it can’t do what it does.

Overview of interfaces in TypeScript

One of TypeScript’s core tenets is that type checking focuses on the shape that related values have. This is sometimes called a “duck type” or a “structural subtype”. In TypeScript, interfaces play a role in naming these types and are a powerful way to define “code conventions” within your code and outside of your project.

What is an interface

Interfaces can be used to describe objects, to name and parameterize object types, and to compose new object types from existing named object types.

This simple interface defines two properties and a method of the Employee object.

interface Employee {
    firstName: string;
    lastName: string;
    fullName(): string;
}
Copy the code

The interface does not initialize or implement properties declared in it. This is because the interface’s only job is to describe types. It defines what is required by the code protocol, and the variable, function, or class that implements the interface satisfies the protocol by providing the required implementation details.

This example implements the interface by declaring a variable of type Employee. It implements the convention by passing in the values of the firstName and lastName attributes and specifying that the fullName method uses the firstName and lastName attributes together and returns the result.

let employee: Employee = { firstName : "Emil", lastName: "Andersson", fullName(): string { return this.firstName + " " + this.lastName; }} // Type check intellisense prompts employee.firstName = 10; //* Error - Type 'number' is not assignable to type 'string'Copy the code

Why interfaces are used in TypeScript

  • Create a shorthand name for a common type. Even with a simple interface, such as the one declared in the previous example, you can enjoy the benefits of Intellisense and type checking.
  • Consistency is maintained in a set of objects because each object implementing the interface runs under the same type definition. An object that implements an interface must implement all the required members of the interface. Therefore, the TypeScript compiler throws an error if all required parameters of the correct type are not passed.
  • Describes existing JavaScript apis and clarifies function parameters and return types. This is especially useful when using JavaScript libraries such as jQuery. Interfaces give you a clear idea of the expected and return values of functions without having to revisit the documentation repeatedly.

What is the difference between an interface and a type alias?

It works but it’s not good

The above Employee interface can also be represented as a type alias using the type key:

type Employee = {
    firstName: string;
    lastName: string;
    fullName(): string;
}
Copy the code

A type alias is a definition of a data type, such as union, primitive, intersection, tuple, or any other type. Interfaces, on the other hand, are a way of describing data shapes, such as objects. Type aliases can be used like interfaces; But there are some subtle differences. The main difference is that the type alias cannot be reopened to add new properties, and the interface is always extensible. In addition, unions or tuples can only be described using type aliases.

Attribute types instructions The sample
Must be All attributes are required unless otherwise specified. firstName: string;
optional Add a question mark at the end of the attribute name (?). Use this property for attributes that are not required. This prevents the type system from raising an error when it omits the attribute. firstName? : string;
read-only Add the readonly keyword before the property name. Use this property for properties that should only be modified when the object is first created. readonly firstName: string;

Declare an interface with members

Declare an interface named IceCream that contains two attributes: flavor as string and flavor as number. The scoops

interface IceCream {
   flavor: string;
   scoops: number;
}
Copy the code

Now you can implement the new interface

let iceCream: IceCream = {
   flavor: 'vanilla',
   scoops: 2
}
​
console.log(iceCream.flavor);
Copy the code

Next, create a function at the bottom called tooManyScoops that uses the IceCream interface as the parameter type. This function checks the number of spoons in the IceCream object and returns a message based on the result. To test your work, pass the object {flavor: ‘vanilla’, scoops: 5} as a parameter and check the result by returning it to the console.

function tooManyScoops(dessert: IceCream) { if (dessert.scoops >= 4) { return dessert.scoops + ' is too many scoops! '; } else { return 'Your order will be ready soon! '; } } console.log(tooManyScoops({flavor: 'vanilla', scoops: 5}));Copy the code

After compiling, you can see the result in The Chrome Console and see the code in source and see that JS does not support interfaces