Introduction to Interfaces
Learn about some of the common features of object-oriented programming and see how interfaces work in TypeScript.
We'll cover the following
Object-oriented programming in TypeScript
TypeScript brings a variety of language enhancements to modern JavaScript development. This includes the primitive types, like string
, number
, boolean
, undefined
, and never
, as well as features brought in from multiple ECMAScript standards, like let
, const
, and optional chaining. TypeScript, therefore, allows us to use these enhanced language features from future JavaScript standards in our code right now, and it takes care of generating the correct JavaScript based on our runtime target.
The ECMAScript standard published in 2015, known as ES6, introduced the concept of classes and inheritance. JavaScript programmers, however, have been able to create classes and use object-oriented programming techniques for many years by using what is known as the closure design pattern and the prototype design pattern. However, the creation of JavaScript objects through closures has been more by convention than being baked directly into the language.
TypeScript has supported the object-oriented concepts of interfaces, classes, and inheritance since its earliest versions. Remember that it generates JavaScript and, as such, is capable of converting the classes that we construct today into older-style JavaScript closures if we are targeting older versions of the JavaScript runtime. This means that no matter what JavaScript runtime we are targeting, the TypeScript compiler will take care of generating the correct JavaScript.
We’ll now explore the basics of interfaces and how they can be used in TypeScript to improve the quality of our code.
Interfaces
We discussed how TypeScript uses duck typing to assess if two objects are compatible. These typing rules govern whether an object can be assigned to another and compares the properties of one object to the other.
Interfaces provide us with a mechanism to define what properties an object must implement and is, therefore, a way for us to define a custom type. By defining an interface, we are describing the properties and functions that an object is expected to have in order to be used by our code.
To illustrate these concepts, consider the following code:
Get hands-on with 1400+ tech skills courses.