#5140Medium

Trunc

Implement the type version of ```Math.trunc```, which takes string or number and returns the integer part of a number by removing any fractional digits. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement a type-level version of Math.trunc that takes a string or number type and returns the integer part by removing any fractional digits.

Challenge Instructions: Trunc

Medium

Implement the type version of Math.trunc, which takes string or number and returns the integer part of a number by removing any fractional digits.

For example:

[object Object]

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

ChallengeSolution
type cases = [
  Expect<Equal<Trunc<0.1>, '0'>>,
  Expect<Equal<Trunc<0.2>, '0'>>,
  Expect<Equal<Trunc<1.234>, '1'>>,
  Expect<Equal<Trunc<12.345>, '12'>>,
  Expect<Equal<Trunc<-5.1>, '-5'>>,
  Expect<Equal<Trunc<'.3'>, '0'>>,
  Expect<Equal<Trunc<'1.234'>, '1'>>,
  Expect<Equal<Trunc<'-.3'>, '-0'>>,
  Expect<Equal<Trunc<'-10.234'>, '-10'>>,
  Expect<Equal<Trunc<10>, '10'>>,
]

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

type Trunc<T extends string | number> =
  `${T}` extends `${infer Int}.${string}`
    ? Int extends '' | '-'
      ? `${Int}0`
      : Int
    : `${T}`;

How it works:

This challenge helps you understand template literal type inference and string parsing at the type level, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge