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).
let x = 1
let y = 1 as const
type cases1 = [
Expect<Equal<Integer<1>, 1>>,
Expect<Equal<Integer<1.1>, never>>,
Expect<Equal<Integer<1.0>, 1>>,
Expect<Equal<Integer<1.0>, 1>>,
Expect<Equal<Integer<0.5>, never>>,
Expect<Equal<Integer<28.0>, 28>>,
Expect<Equal<Integer<28.101>, never>>,
Expect<Equal<Integer<typeof x>, never>>,
Expect<Equal<Integer<typeof y>, 1>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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.