Structural Typing and Algebraic Data Types

(with Typescript)

I'm Grant BTW

What's ahead?

  • Why?
  • Very brief refresher on static types in general
    • Examples with TS
  • What is structural typing (as opposed to nominal typing)?
    • Examples with TS
  • What are algebraic data types?
    • Examples with TS
  • Fun ways to combine them?
    • Examples with TS

Why talk about structural typing and algebraic data types?

  • They add a lot of flexibility to static type systems
  • Still allow compiler to check correctness
  • You'll probably encounter them in the future if you haven't already
  • I think they're cool

Why Typescript?

  • Familiar and has both features.
  • Other langs with Algebraic Data Types
    • C++, F#, Haskell, Kotlin, Perl, Rust
  • with Structural Typing
    • Go
  • with both
    • Julia, OCaml, Scala, Swift

Refresher: Static types

  • Often a feature of compiled languages
  • Define explicitly ahead of time what properties are available on variables and parameters
  • Allows compiler to do up front correctness checks on your code

Examples with TS

Structural Typing

Before we get too far: What is Nominal typing?

  • It's what we're probably used to.
  • Suppose we have a function that requires a Vehicle parameter: What can we pass in?
    • In other words: What counts as a Vehicle?
  • A Vehicle is a Vehicle
  • A Boulder is not a Vehicle
    • "Boulder" != "Vehicle"
  • A Truck that extends Vehicle is a Vehicle
    • Explicitly made compatible by the author

How is Structural typing different?

...compatibility and equivalence are determined by the type's actual structure or definition and not by other characteristics such as its name...

EngineerScotty, Pengo, and Anonymous Wikipedia Editor at

Examples with TS

Algebraic Data Types

Algebraic Data Types

  • Combine existing types to create new types
  • Combine Cat and Dog to create a CatDog type
  • Combine TextInput and NumberInput to create a GenericInput type
  • Mainly: Products and Sums

Product Types

  • Think AND
  • Operates on fields of types (including properties and methods)
  • Cat ⋅ Dog has all fields of Cat AND all fields of Dog
  • In TS: called an "Intersection"; operator is &

Sum Types

  • Think OR
  • Creates variants of a type
  • TextInput + NumberInput could be a TextInput OR a NumberInput
  • Need to determine which variant you have before using it, typically using a tag
  • tags for variants could be handled by compiler or manually, depending on the language
  • In TS: called an "(Untagged) Union"; operator is |

Examples with TS