Skip to content

Latest commit

 

History

History
87 lines (75 loc) · 3.57 KB

structural-typing.md

File metadata and controls

87 lines (75 loc) · 3.57 KB

Structural Typing

Most programming languages use either nominal typing or structural typing.

For example:

interface Cat {
    legs: number;
}

interface Dog {
    legs: number;
}
  • In nominal typing, Cat and Dog are different types, because their names are different.
  • In structural typing, Cat and Dog are the same type, because their structure is the same.

Structural typing is closer to the original concept of object-oriented programming. It allows us to work with data based on its behaviours, rather than its name.

At first glance, structural typing is less robust than nominal typing. If you pass in the wrong type of data, but it happens to have the same structure as the correct type of data, the compiler cannot warn you about your mistake.

However, structural typing makes it easier to reuse code - and reusing tested code is an important way to improve the robustness of an app. We don't have to put up with limitations or bugs in existing types that we cannot modify. We can make our own types, and as long as they have the same structure, we can use them wherever the existing type is accepted.

And, you can reduce the risks of passing in the wrong type of data by using type branding on classes and interfaces.

Typescript uses structural typing, because the underlying Javascript engines use structural typing.