typehero typescript challenge Day Six - Filtering The Children (part 1) - Advent of TypeScript
Series
Advent of TypeScript Solutions
Episode 6 • Season 1

Day 6 | Filtering The Children (part 1) | Typehero Advent of TypeScript Challenge

327Reads
6 December, 2023

Challenge Explanation

Some context of the story, so Santa, who likes to have control over his naughty and nice lists, needs a way to filter out kids based on their behavior. He's asking the engineering elves, who are already not thrilled about their pay situation, to come up with a solution. They need to create something that can filter out either the 'naughty' or 'nice' kids from Santa's list, depending on what he wants at the moment. The engineering team, already busy and a bit grumpy, agrees to work on this without the usual project management formalities.

TypeScript Concept Involved

The concept we’re dealing with here is a TypeScript utility type. Specifically, this is about creating a conditional type that can filter out certain types from a union. It's like sorting through a mixed bag of items and picking out only the ones you need.

Solution

So, fo the solution, we need to define FilterChildrenBy as a generic type that takes two parameters: a union of types (representing the children's statuses) and the type we want to exclude. We use TypeScript's conditional types and the Exclude utility type to do this. Here’s how it can be done:

type FilterChildrenBy<Children, ExcludeStatus> = Exclude<Children, ExcludeStatus>;
  • Children is a union type of the different statuses (like 'nice', 'naughty').
  • ExcludeStatus is the status we want to filter out.
  • Exclude is a TypeScript utility that creates a type by excluding from Children all union members that are assignable to ExcludeStatus.

Link to Day one Challenge on TypeHero.dev:- https://typehero.dev/challenge/day-6

That's it! See you in the next Day Challenge.