Given a number, your type should return its square. Learn tuple manipulation, array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a Square type that computes the square of a given number at the type level, including support for negative numbers.
Given a number, your type should return its square.
Change the following code to make the test cases pass (no type check errors).
type Abs<N extends number> = `${N}` extends `-${infer P extends number}` ? P : N
type MakeTuple<N extends number, T extends unknown[] = []> =
T['length'] extends N ? T : MakeTuple<N, [...T, unknown]>
type Multiply<A extends number, B extends number, Result extends unknown[] = [], Count extends unknown[] = []> =
Count['length'] extends A
? Result['length']
: Multiply<A, B, [...Result, ...MakeTuple<B>], [...Count, unknown]>
type Square<N extends number> = Multiply<Abs<N>, Abs<N>>How it works:
Abs<N> converts a negative number to its positive counterpart by using template literal types. It checks if the string representation of N starts with -, and if so, infers the positive portion P.MakeTuple<N> builds a tuple of length N by recursively adding elements until T['length'] equals N. This is a common pattern for converting numeric literals to countable structures.Multiply<A, B> performs type-level multiplication by repeatedly concatenating a tuple of length B a total of A times. The Count tuple tracks how many times we have added, and Result accumulates the total elements. When Count['length'] reaches A, we return Result['length'].Square<N> simply calls Multiply with the absolute value of N for both arguments, since squaring a negative number produces a positive result.This challenge helps you understand type-level arithmetic using tuple length counting and how to apply these concepts in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount