#10969Medium

Integer

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.

Challenge Instructions: Integer

Medium

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).

ChallengeSolution
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>>,
]

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

type Integer<T extends number> =
  number extends T
    ? never
    : `${T}` extends `${bigint}`
      ? T
      : never;

How it works:

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.

Share this challenge