Explanation
This TypeScript challenge involves creating a type FindSanta that takes a tuple of strings as its input and returns the index of the string '🎅🏼' (Santa) if it exists in the tuple. If Santa is not found, it should return never. This problem tests your understanding of TypeScript's conditional types, indexed access types, and tuple manipulation.
We need to create a FindSanta type that scans through a tuple of strings representing a forest. It should locate the index of Santa ('🎅🏼') in the tuple. If Santa is not found, the type should resolve to never.
TypeScript Concept Involved
Conditional Types: TypeScript's conditional types allow types to be chosen based on conditions.
Indexed Access Types: These types help to access the type of a specific index in a tuple or array.
Tuple and Array Types Manipulation: Understanding how to iterate and manipulate tuple types is essential for solving this challenge.
Type Recursion: A recursive approach may be required to iterate through the tuple.
Solution
type FindSanta<T, Index extends number[] = []> = T extends [infer First, ...infer Rest]
? First extends '🎅🏼'
? Index['length']
: FindSanta<Rest, [...Index, 0]>
: never;
- The type FindSanta takes two generic parameters: T (the tuple) and Index (an array of numbers representing the current index, initialized as an empty array).
- We use a conditional type to check if T extends the pattern [infer First, ...infer Rest], which means T can be split into a first element and the rest of the elements.
- If First is equal to '🎅🏼', then the type resolves to the current index, calculated by the length of the Index array.
- If First is not '🎅🏼', the function is recursively called with the rest of the tuple (Rest) and the index incremented by adding 0 to the Index array.
- If the tuple is exhausted without finding Santa, the type resolves to never.
Link to Day one Challenge on TypeHero.dev:- https://typehero.dev/challenge/day-12
That's it! See you in the next Day Challenge. Still 13 more days to go until these challege ends. It feels like forever