Type systems are typically categorized as either structural or nominal. Languages like Java and Scala have primarily nominal type systems, whereas a language like Typescript has a structural type system. Let’s take a brief look at both systems.
In a nominal typing system, type compatibility is checked using the name of the types. If they do not have the same name, then they are not compatible; end of story. **If **Typescript had a nominal typing system the type check for the last line would fail:
Typescript uses structural typing to decide whether two types are compatible with one another or not. What do we mean by structural typing? Well, let’s consider the following code snippet:
To determine whether the type of the constant color
(RGBA
) is compatible with the type of serializeColor
’s parameter x
(RGB
) the type system must verify that each member of RGB
has a corresponding compatible member in RGBA
. In this case, RGB
has a single member color
for which RGBA
has a corresponding member with the same type — [number, number, number]
— and so it passes the type check. Notice how the type system ignores the additional members that exist on RGBA
(alpha).
#typescript #type-safe #type-systems