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.
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).
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'>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type Trunc<T extends string | number> =
`${T}` extends `${infer Int}.${string}`
? Int extends '' | '-'
? `${Int}0`
: Int
: `${T}`;How it works:
T is first converted to a string template literal via `${T}`, which normalizes both number and string inputs into a string representation`${infer Int}.${string}`, where Int captures everything before the dot and string discards the fractional partInt is returned -- but with a special check: if Int is empty (e.g., input .3) or just a minus sign (e.g., input -.3), we append 0 to produce '0' or '-0' respectivelyThis 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.