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:
type A = Trunc<12.34> // 12Change the following code to make the test cases pass (no type check errors).
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.
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