O'Reilly logo

TypeScript Blueprints by Ivo Gabe de Wolff

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Understanding the structural type system

TypeScript uses a structural type system. What that means can be easily demonstrated using the following example:

class Person { 
  name: string; 
} 
class City { 
  name: string; 
} 
const x: City = new Person(); 

In languages like C#, this would not compile. These languages use a nominal type system. Based on the name, a Person is not a City. TypeScript uses a structural type system. Based on the structure of Person and City, these types are equal, as they both have a name property. This fits well in the dynamic nature of JavaScript. It can, however, lead to some unexpected behavior, as the following would compile:

class Foo { 
   
} 
const f: Foo = 42; 

Since Foo does not have any properties, every value would be assignable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required