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.
The best way to learn how interfaces work is to start with a simple example:
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.
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.
Thanks goes to these wonderful people (emoji key):