TypeScript for real code · Chapter 22 of 36

Strings with rules

By the end of this chapter you can write a string's format into its type, build string types from unions, and take strings apart with infer. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Types that compute types
  • 4 tasks
  • TypeScript
  • In the all labs plan

The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.

Why you need this

Ravi has three bugs, and all three are strings in the wrong format. The rider app looked up ord-42 and found nothing, because Tapri's order ids are order-42. The kitchen screen showed large-2 when the cooks read sizes in capitals. And Bunty's handler onPlace never ran, because the event is called placed. Kabir adds a fourth: the router builds a link from a route and an object of params, and a misspelt param leaves :orderId in the link.

So far a string is either string, which allows anything, or a union of literals, which you would have to write out by hand: every order id from 1 to forever. Neither one says "order-, then a number".

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    OrderId: order- followed by a number

    Tapri's order ids are order- followed by a number, like 'order-42'. Make OrderId a template literal type, so 'ord-7' and 'order-chai' are type errors and a plain string is not an OrderId. makeOrderId(42) is 'order-42' and has the type OrderId.

    isOrderId(text) checks a string from a form: it is true for 'order-42', and false for 'ord-42', 'order-' and 'order-chai'. Make it a type predicate, so once isOrderId(text) is true, TypeScript knows text is an OrderId. Its body must check for digits after order-, not only the start.

  2. Task 2

    KitchenTag: the size in capitals and a number

    The kitchen screen shows sizes in capitals. SizeCode is exactly 'CUTTING' | 'REGULAR' | 'LARGE': build it from Size with a built-in type, not by writing the three names again. A KitchenTag is a SizeCode, a dash and a number, like 'REGULAR-1', so 'LARGE-two' and 'HUGE-1' are type errors.

    kitchenTag(size, qty) keeps its parameters (a SizeCode and a number) and returns a KitchenTag: kitchenTag('LARGE', 2) is 'LARGE-2', and kitchenTag('large', 2) is a type error.

  3. Task 3

    OrderHandlers: an on handler for every event

    An event's handler is on followed by the event's name with a capital letter: HandlerName<'placed'> is 'onPlaced' and HandlerName<'outForDelivery'> is 'onOutForDelivery'.

    OrderHandlers has one optional handler for each OrderEvent, under its handler name, so its keys are exactly 'onPlaced' | 'onBrewing' | 'onDelivered'. Each handler takes an OrderId and returns nothing, so a handler that takes a number is a type error, and so is onPlace. { onDelivered: (id) => {} } on its own is fine. Build it from OrderEvent and HandlerName; do not list the names by hand.

  4. Task 4 · interview question

    Interview: buildPath, the params a route needs

    ParamNames<R> is the union of the names after each colon in a route: ParamNames<'/orders/:orderId'> is 'orderId', ParamNames<'/orders/:orderId/items/:itemId'> is 'orderId' | 'itemId', ParamNames<'/riders/:riderId/orders'> is 'riderId', and ParamNames<'/menu'> is never. RouteParams<R> is an object with a string for each of them: RouteParams<'/riders/:riderId'> is { riderId: string }.

    Make buildPath generic in the route, so its params must be RouteParams of that route: buildPath('/orders/:orderId', { orderId: 'order-7' }) is '/orders/order-7', and { id: 'order-7' } for that route, or a missing param, is a type error. The body stays as it is. Dev will ask you to explain how the type walks the route.

What you will learn

  • Template literal types: backticks in a type, with placeholders such as ${number}, describe a format.
  • Building strings from unions: placeholders hold unions, and Uppercase and Capitalize change their case, even inside a mapped type's key names.
  • Taking strings apart: infer in a string pattern, and a type that calls itself to handle the rest of the string.

More in Types that compute types

Build "Strings with rules" yourself

Tapri’s codebase grows, and types keep it honest. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.