Skip to main content

Interfaces

One of the basic tenets of TypeScript is that typing is based on the structure of objects. This type of typing is called implicit or` duck '- an object is classified as a particular type (class, interface) if it has (implements) all its properties and methods. Interfaces in TS are used just to describe the types you need.

Simple example#

The best way to learn how interfaces work is to start with a simple example:

Playground Link

function giveFruit(fruit: { name: string }) {
console.log('Give to me ' + fruit.name)
}
let myFruits = { name: 'Banana', sweetness: 7, bones: false }
giveFruit(myFruits)

The giveFruit () function has a single parameter that requires the passed object to have a property named name of type string. Note that our object actually has more properties than required, but the compiler only checks to see if at least those required are present and match the required types.

Let's write the same example to test the name property with the string type, but using interfaces.

Playground Link

interface Fruit {
name: string;
sweetness: number;
bones: boolean;
}
function giveFruit(fruit: Fruit) {
console.log('Give to me ' + fruit.name)
}
let myFruits = { name: 'Banana', sweetness: 7, bones: false }
giveFruit(myFruits)

The Fruit interface is the name we can now use to describe the requirement in the previous example. It still represents the presence of a single property named name of type string. Please note that we did not need to explicitly indicate that the object we pass to the giveFruit () function inherits this interface, as it might in other languages. Only the sample is important here. If the object that we pass to the function meets the listed requirements, then everything is allowed.

It's worth noting that type checking does not require that these properties be in any order, but only that the properties required by the interface are present and of the required type.

Payment#

Now you are on a stripped-down version of the site, after subscribing to Patreon, you will get full access to the training course, as well as access to our server's private channels in Discord.

Download our mobile application or get tested in our JavaScript telegram bot, and also subscribe to our news.

Become a Patron!

Sumerian school

Links#

  1. TypeScriptLang
  2. Interfaces

Contributors โœจ#

Thanks goes to these wonderful people (emoji key):


IIo3iTiv

๐Ÿ“–

Dmitriy Vasilev

๐Ÿ’ต

Become a Patron!