typescript
  • A crash guide to Typescript
  • Intro
    • What Typescript IS for?
    • What Typescript is NOT for?
    • Setting up tsconfig.json
  • Types are spooky! (How types work?)
  • Handling mutable code
  • The primitive types
  • Interfaces or Type Aliases? Oh, my!
  • The `class`, a creature which spans both realms
  • Structural typing
  • Control Flow Analysis
  • More advanced type syntaxes for another day
  • Generics
  • Modules
  • 3rd-party types
  • Epilogue
Powered by GitBook
On this page

Was this helpful?

Structural typing

Definition:

In order to determine if two types are assignable, the compiler exhaustively compares all their properties.

This contrasts with nominal typing, which works like:

Two types only are assignable if they were created from the same constructor OR from an explicitly related constructor. (explicitly related usually means: extends or implements).

Given two classes A and B:

class A {
    name
    lastName
}

class B {
    name
    lastName
    age
}

Now let a function require A as input.

function requireA(person: A) {}
requireA(new A()) //ok
requireA(new B()) //ok
requireA({ name: 'Barbra', lastName: 'Streisand' }) //ok
requireA({ name: 'Barbra', lastName: 'Streisand', age: 77 }) //error
  • The function accepted B as input since its properties were considered assignable;

  • This would not be allowed on nominal typing, since it would require B to explicitly extend or implement A;

  • Since we are just comparing properties, just directly passing a conforming object also works;

  • The last line errors because TS applies a special rule which enforces exact properties if the argument is a literal;

PreviousThe `class`, a creature which spans both realmsNextControl Flow Analysis

Last updated 3 years ago

Was this helpful?