Welcome!

Blog Feed Post

Learning TypeScript: Structural vs nominal typing systems

After completing the second edition of the book “Angular Development with TypeScript“, my colleague Anton Moiseev and I started working on yet another book for Manning. This one will be called “Get Programming with TypeScript” and its tentative Table of Content is available here.

This book will cover the main syntax elements of the TypeScript language, and to make the book more interesting, we’ll also develop a blockchain app.
Meanwhile, I’ll start a series of blogs on the TypeScript-related topics. This one is about TypeScript’s structural type system.

A primitive type has just a name (e.g. number) while a more complex type like an object or class has a name and some structure represented by properties (e.g. a class Customer has properties name and address).

How would you know if two types are the same or not? In some languages (e.g. Java) two types are the same if they have the same names, which represents a nominal type system. In Java, the last wouldn’t compile because the names of the classes are not the same even though they have the same structure:

class Person {
	String name;
}

class Customer {
	String name;
}

Customer cust = new Person();  // compiler's error

But TypeScript and some other languages use the structural type system. In the following code snippet I re-wrote the above code snippet in TypeScript:

class Person {
	name: string;
}

class Customer {
	name: string;
}

const cust: Customer = new Person(); // no errors  

This code doesn’t report any errors because TypeScript uses structural type systems, and since both classes Person and Customer have the same structure, it’s OK to assign an instance of one class to a variable of another.

Moreover, you can use object literals to create objects and assign them to class-typed variables or constants as long as the shape of the object literal is the same. The following code snippet will compile without errors:

class Person {
	name: string;
}

class Customer {
	name: string;
}

const cust: Customer = { name: 'Mary' };   
const pers: Person = { name: 'John' };

Our classes didn’t define any methods, but if both of them would define a method(s) that has the same signature (name, arguments, and the return type) they would also be compatible.

What if the structure of Person and Customer are not exactly the same? Let’s add a property age to the class Person as is the following listing:

class Person {
    name: string;
    age: number;    // 1
}

class Customer {
	name: string;
}

const cust: Customer = new Person(); // still no errors  

1 We’ve added this property

Still no errors! TypeScript sees that Person and Customer have the same shape. We want to use the constant of type Customer (it has the property name) to point at the object of type Person (it also has the property name).

Follows the link https://bit.ly/2MbHvpH and you’ll see this code in TypeScript playground (a REPL to try code snippets in TypeScript and compile them into JavaScript). Click Ctrl-Space after the dot in cust. and you’ll see that only the name property is available even though the class Person has also the property age.

Homework: Can the class Customer have more properties than Person?
In the previous code snippet, the class Person had more properties than Customer and the code compiled without errors. What if the class Customer has more properties than Person? Would the following code compile? Explain your answer.

class Person {
    name: string;
}

class Customer {
    name: string;
    age: number;
}

const cust: Customer = new Person();

Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

Latest Stories
CloudEXPO New York 2018, colocated with DevOpsSUMMIT and DXWorldEXPO New York 2018 will be held November 12-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI and Machine Learning to one location.
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of computational needs for many industries. Their solutions provide benefits across many environments, such as datacenter deployment, HPC, workstations, storage networks and standalone server installations. ICC has been in business for over 23 years and their phenomenal range of clients include multinational corporations, universities, and small busines...
This sixteen (16) hour course provides an introduction to DevOps, the cultural and professional movement that stresses communication, collaboration, integration and automation in order to improve the flow of work between software developers and IT operations professionals. Improved workflows will result in an improved ability to design, develop, deploy and operate software and services faster.
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
Authorization of web applications developed in the cloud is a fundamental problem for security, yet companies often build solutions from scratch, which is error prone and impedes time to market. This talk shows developers how they can (instead) build on-top of community-owned projects and frameworks for better security.Whether you build software for enterprises, mobile, or internal microservices, security is important. Standards like SAML, OIDC, and SPIFFE help you solve identity and authenticat...
The digital transformation is real! To adapt, IT professionals need to transform their own skillset to become more multi-dimensional by gaining both depth and breadth of a wide variety of knowledge and competencies. Historically, while IT has been built on a foundation of specialty (or "I" shaped) silos, the DevOps principle of "shifting left" is opening up opportunities for developers, operational staff, security and others to grow their skills portfolio, advance their careers and become "T"-sh...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
Hackers took three days to identify and exploit a known vulnerability in Equifax’s web applications. I will share new data that reveals why three days (at most) is the new normal for DevSecOps teams to move new business /security requirements from design into production. This session aims to enlighten DevOps teams, security and development professionals by sharing results from the 4th annual State of the Software Supply Chain Report -- a blend of public and proprietary data with expert researc...
Lori MacVittie is a subject matter expert on emerging technology responsible for outbound evangelism across F5's entire product suite. MacVittie has extensive development and technical architecture experience in both high-tech and enterprise organizations, in addition to network and systems administration expertise. Prior to joining F5, MacVittie was an award-winning technology editor at Network Computing Magazine where she evaluated and tested application-focused technologies including app secu...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
Having been in the web hosting industry since 2002, dhosting has gained a great deal of experience while working on a wide range of projects. This experience has enabled the company to develop our amazing new product, which they are now excited to present! Among dHosting's greatest achievements, they can include the development of their own hosting panel, the building of their fully redundant server system, and the creation of dhHosting's unique product, Dynamic Edge.
This session will provide an introduction to Cloud driven quality and transformation and highlight the key features that comprise it. A perspective on the cloud transformation lifecycle, transformation levers, and transformation framework will be shared. At Cognizant, we have developed a transformation strategy to enable the migration of business critical workloads to cloud environments. The strategy encompasses a set of transformation levers across the cloud transformation lifecycle to enhance ...