#27133Medium

Square

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.

Challenge Instructions: Square

Medium

Given a number, your type should return its square.

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
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>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

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:

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.

Share this challenge