Bitpath

TypeScript in Depth

TypeScript as its own language: inference, unions, generics and types that compute other types, each one explained against what Python does. Then the JavaScript underneath, and where types stop and run-time data begins.

  • Intermediate
  • 4 units, 12 lessons, 156 exercises
  • TypeScript
  • Builds on some JavaScript, or JavaScript: Zero to Hero or TypeScript: Zero to Hero

Unit 01 · 3 lessons

Types

Read what the compiler infers, and model data so that wrong states do not compile

  1. > start01Inference
  2. 02Object types
  3. BOSSUnions and narrowing
Unit prize
  1. 01
    Inference

    What the compiler works out without being told

  2. 02
    Object types

    Shapes, not names: structural typing and its one extra check

  3. BOSS
    Unions and narrowing

    Model a request so that impossible states cannot be written

Read the unit guide

TypeScript checks your program without running it. Most types are never written down: the compiler infers them from values. let n = 5 is a number from then on, and const dir = "up" has the literal type "up", because a const can never hold anything else. Annotate what cannot be inferred, which is mostly function parameters.

Two types mean "anything", and they are opposites. any switches checking off and spreads to everything it touches. unknown accepts any value but lets you do nothing with it until you have narrowed it with a check such as typeof v === "string".

With strict null checks, undefined and null are their own types. A lookup that can miss returns T | undefined, and you must deal with the miss: ?. to stop early, ?? for a default (it only replaces null and undefined, unlike ||).

Object types are structural: a value fits if it has the required members, whatever it is called. That is Python's duck typing, checked before the program runs. A fresh object literal gets one extra check, for properties the target type does not know, which is how typos are caught.

A union A | B is a value that is one or the other. You may only use what both share until a check narrows it. Give each case a literal tag (kind: "ok") and a switch on the tag narrows to exactly one case: a discriminated union. Assign the leftover to never in the default branch and the compiler tells you when a new case is not handled.

The classic pitfall: every type is erased when the code is compiled. readonly, ! and annotations change what the compiler accepts, never what happens at run time.

Unit 02 · 3 lessons

Generics

Write functions and types that work over many types without forgetting which one they were given

  1. 01Generics
  2. 02Keyof and Lookups
  3. BOSSUtility Types by Hand
Unit prize
  1. 01
    Generics

    Type parameters, constraints and defaults

  2. 02
    Keyof and Lookups

    Keys as types, and the type behind a key

  3. BOSS
    Utility Types by Hand

    Rebuild Partial, Readonly, Pick, Omit and Record, then type an update function

Read the unit guide

A generic function has a type parameter: a variable that stands for a type. function first<T>(xs: T[]): T says "an array of some T goes in, one T comes out", and the compiler fills in T from the argument at each call. You rarely write it yourself. Python's TypeVar is the same idea.

A bare T could be anything, so inside the function you may do nothing with it. A constraint, T extends { length: number }, says what every T must at least have, and that much becomes usable. The caller still gets back the exact type passed in, which is what a constraint gives you over a plain parameter type.

keyof T is the union of the property names of T, and T[K] is the type of property K. Together they type code that takes a key: get<T, K extends keyof T>(o: T, k: K): T[K] rejects a misspelt key and returns the right type for each real one. In a type position, typeof value gives the type of a value, so one object can be the source of both.

A mapped type loops over keys: { [K in keyof T]?: T[K] } is every property of T, made optional. The built-in utility types are one-liners of this kind: Partial, Readonly, Pick, Omit, Record. They let you derive a type from another instead of writing a near copy that drifts.

The classic pitfall is a type parameter that appears once. function log<T>(x: T): void links nothing to nothing, and unknown says the same. A generic earns its place when it ties an input to an output, or one input to another.

Unit 03 · 3 lessons

Computing with Types

Write types that ask questions of other types, and let one description drive a whole API

  1. 01Conditional Types
  2. 02Literal Types at Work
  3. BOSSA Typed API Client
Unit prize
  1. 01
    Conditional Types

    Types that ask a question, and infer the answer

  2. 02
    Literal Types at Work

    as const, template literal types, satisfies, and unions against enums

  3. BOSS
    A Typed API Client

    One route map drives the parameters and the result of every request

Read the unit guide

A conditional type is an if for types: T extends U ? X : Y gives X when T is assignable to U, and Y otherwise. Inside the extends pattern, infer R names a piece of the type being matched, so the result can use it. ReturnType and Awaited are both one conditional type with one infer.

Give a conditional type a union and it is applied to each member separately, and the results are unioned. Mapping a member to never removes it, which makes a conditional type a filter over a union. Exclude is exactly that.

as const freezes a value's type at its narrowest: literals stay literal and arrays become readonly tuples. Then typeof can turn the value into types, so a list written once drives both the run-time code and the checks. Template literal types build string types from unions, one string per combination. satisfies checks a value against a type without widening the value to it.

A union of string literals does most of what an enum does, costs nothing at run time, and accepts plain strings from JSON. An enum is a real object in the compiled code and a closed type of its own.

Put together, these let one type describe an API: a map from route to input and output. A generic request<R extends keyof Api> looks up both from the route it is given, so a misspelt route, a wrong parameter and a wrong field on the result all fail to compile.

The classic pitfall is believing these types at the edges. They compute over what you declared, and a declaration can be wrong. Inside request, the response body is still cast with as, and nothing has checked it.

Unit 04 · 3 lessons

Types Meet Runtime

Know where the types stop: at the edges of the program, and in the JavaScript that actually runs

  1. 01Boundaries
  2. 02The JavaScript Underneath
  3. BOSSA Strict Project
Unit prize
  1. 01
    Boundaries

    Data from outside is unknown until checked at run time

  2. 02
    The JavaScript Underneath

    this, closures, prototypes, equality, truthiness and promises

  3. BOSS
    A Strict Project

    Move a JavaScript file to strict TypeScript, one error at a time

Read the unit guide

Types are erased when TypeScript is compiled. What runs is JavaScript, and it has never heard of your interfaces. Inside the program that is fine, because the compiler checked every step. At the boundary, where data arrives from a server, a file or JSON.parse, nobody has checked anything.

JSON.parse returns any, so a wrong shape flows in without a murmur. Type the incoming value as unknown and prove its shape at run time. A type guard is a function returning v is User: where it says yes, the compiler narrows. An assertion function, asserts v is User, throws instead of answering no. as does neither. It is a claim, it emits no code, and it converts nothing.

The language underneath has its own rules, and several differ from Python. this is set by how a function is called, so a method passed as a callback loses it; arrow functions keep the surrounding this. === compares objects by identity. Empty arrays and objects are truthy. typeof null is "object". Classes are a layer over prototypes, and an async function always returns a promise.

A project is configured in tsconfig.json. strict turns on a family of checks, chiefly no implicit any and strict handling of null and undefined. Code without types is described by declaration files, .d.ts, which hold signatures and no bodies. A JavaScript codebase moves over a file at a time, with both kinds of file living side by side.

The classic pitfall is treating a green compile as proof about the outside world. as, !, any and a .d.ts are all promises made by a person. The compiler believes each of them, and none is checked when the program runs.

Learn TypeScript in Depth on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy