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 cases = [
Expect<Equal<Square<0>, 0>>,
Expect<Equal<Square<1>, 1>>,
Expect<Equal<Square<3>, 9>>,
Expect<Equal<Square<20>, 400>>,
Expect<Equal<Square<100>, 10000>>,
Expect<Equal<Square<101>, 10201>>,
// Negative numbers
Expect<Equal<Square<-2>, 4>>,
Expect<Equal<Square<-5>, 25>>,
Expect<Equal<Square<-31>, 961>>,
Expect<Equal<Square<-50>, 2500>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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.