Please complete type `Integer<T>`, type `T` inherits from `number`, if `T` is an integer return it, otherwise return `never`. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement an Integer<T> type that checks whether a numeric type T is an integer, returning T if it is and never otherwise.
Please complete type Integer<T>, type T inherits from number, if T is an integer return it, otherwise return never.
Change the following code to make the test cases pass (no type check errors).
type Integer<T extends number> =
number extends T
? never
: `${T}` extends `${bigint}`
? T
: never;How it works:
number extends T handles the case where T is the wide number type (not a specific numeric literal). If T is just number, we return never since we cannot determine if an arbitrary number is an integer.T to a string via template literal \${T}`and check if it matches the pattern`${bigint}``.bigint template pattern matches strings that represent integers (like "1", "28", "-5") but does not match strings with decimal points (like "1.1", "0.5").1.0 are normalized by TypeScript to 1, so \${1.0}`becomes"1", which correctly matches the bigint` pattern.An alternative approach uses explicit decimal point detection:
type Integer<T extends number> =
number extends T
? never
: `${T}` extends `${string}.${string}`
? never
: T;This alternative checks if the string representation contains a decimal point, but note it would also accept scientific notation numbers like 3e23 as integers. The bigint approach correctly rejects these since "3e+23" does not match bigint.
This challenge helps you understand template literal types and type narrowing with numeric types, and how to apply these techniques 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