Get In Losers We're Learning

Advanced TypeScript

Objectives

  1. Solidify Fundamentals of Advanced Type Manipulations
  2. Solve Real-World Coding Challenges with TypeScript

A Quick Demo

Where are we going?

  • Type Systems
  • Generic Types
  • Template Literal Types
  • Index Accessed Types
  • Conditional Types
  • Mapped Types

Type Systems

Type systems are how our data is labeled, organized, and related to each other

Nominal Typing

  • Focuses on the name of the type

          class Cat {
            static let numberOfLegs = 4

            func makeSound() {
                print("meow")
            }
          }
          
          class Dog {
            static let numberOfLegs = 4

            func makeSound() {
                print("woof")
            }
          }
          
          var animal = Dog();
          
          // error: cannot assign value of 
          // type 'Cat' to type 'Dog'
          animal = Cat();
          

Structural Typing

  • Focuses on the shape of the type

            class Cat {
              static numberOfLegs = 4;
            
              makeSound() {
                console.log("meow")
              }
            }
            
            class Dog {
              static numberOfLegs = 4;
            
              makeSound() {
                console.log("woof")
              }
            }
            
            let animal = new Dog()
            animal = new Cat() // No error
          

TypeScript Types Are Minimal Requirements


            class Cat {
              static numberOfLegs = 4;
            
              makeSound() {
                console.log("meow")
              }

              scratchFurniture() {

              }
            }
            
            class Dog {
              static numberOfLegs = 4;
            
              makeSound() {
                console.log("woof")
              }
            }
            
            let animal = new Dog()
            animal = new Cat() // No error
          

Why this Matters

  • API Design and Evolution
  • Solidify our Mental Models based on backgrounds
  • Advanced TS Features

Generic Types

Even if you've never written a generic type or function, you have used them.


            const numbers = [1, 2, 3];

            // TypeScript knows doubled is an array
            // of numbers (number[])
            const doubled = numbers.map((num) => num * 2);

            // TypeScript infers the types of accumulator and
            // currentValue as numbers
            const sum = numbers.reduce(
              (accumulator, currentValue) => accumulator + currentValue,
              0
            );
          

There are a lot of ways to think about Generic Types

  • A way to reuse type-level logic
  • A way of writing code that is independent of the specific types that will be used
  • A way to connect your inputs and outputs

Anatomy of "Generics"

Generic Types and Functions

Code Example

Back to Our Example

Current Issues with our Implementation

  • The RequestHandler does Not have access to path
  • No inference / dynamic type handling
  • No TypeScript errors when something is wrongly accessed

Recap

  • Structural Typing
  • Generic Types

Progress on Our Get API

  • Used generic type arguments to wire up our inputs

Template Literal Types

Template literal types allow us to combine string literals

TypeScript will create a new union which applies the template literal type to each member of a union

It works with multiple unions

Let's look at some code

Index Accessed Types

Don't over complicate this one, it's just a way to look up a specific property on another type

Using Index Accessed Types

Don't Forget About Arrays!

Recap

These are similar to JavaScript/TypeScript

  • Template literal types
  • Index accessed types

Progress on Our Get API

We haven't used them yet however...

  • Template literal types: path manipulation
  • Index accessed types: we will be storing and pulling things from arrays!

Top and Bottom Types

Precursor to Conditional Types

Top Type: Contains all types, meaning any other type is assignable to it.

TypeScript has two top types any and unknown

Bottom Type: Nothing is assignable to it except itself

TypeScript has one bottom type never

Ok so What?

Let's focus on bottom types and look at what happens when we combine it with other types

Conditional Types

Conditional types act exactly as conditional statements do in programming

Syntax

Distributivity of Conditional Types

When given a union, conditional types distribute the condition to each member of the union

Let's look at NonNullable

Distributing over the Union

A New and Powerful Syntax

infer is You telling TypeScript

"Hey if it matches this pattern, infer what it is and give me a variable to refer to it by"

Infer in Action

Back to Our Example

Current Issues with our Implementation

  • The RequestHandler does Not have access to path
  • No inference / dynamic type handling
  • No TypeScript errors when something is wrongly accessed

The Plan

Create a union of path params

  1. Break the path into segments
  2. Pull out the path params in a dev friendly way

Let's Start at the End

Pull out the path params in a dev friendly way

Our Approach

We have a path we need to break it into segments

If it was JavaScript

Recap on Conditional Types

  • Behave like ternaries in JavaScript/TypeScript
  • Distribute over unions
  • Give access to a new keyword infer

Recap on the Get API

  • Split our path into segments using conditionals types, index accessed types, and template literals
  • Pulled out path parameters with conditional types and template literals

We Broke it Down... So Now What?

Mapped Types

Create an object type out of a union of a key types

string | number | symbol

Syntax

A Practical Example

Transforming Objects

Let's finish up our type!

Other Neat Mapped Types Functionalities

  • Property Modifiers
  • Key Remapping

Thank You For Your Time

Let's Keep in Touch, I'm David Nicholas

Slides: https://davidnic11.github.io/talk-advanced-typescript/

Example Repo: https://github.com/DavidNic11/examples-advanced-typescript

LinkedIn:

Resources