Skip to content

isInt

Checks whether a value is of integer type.

Basic Usage

typescript
import { isInt } from 'radash'

console.log(isInt(42))           // true
console.log(isInt(3.14))         // false
console.log(isInt('42'))         // false
console.log(isInt(NaN))          // false
console.log(isInt(Infinity))     // false

Syntax

typescript
function isInt(value: any): value is number

Parameters

  • value (any): The value to check

Return Value

Returns a boolean value, true if the value is an integer, false otherwise. Also serves as a TypeScript type guard.

Examples

Basic Type Checking

typescript
import { isInt } from 'radash'

// Integers
console.log(isInt(42))           // true
console.log(isInt(0))            // true
console.log(isInt(-10))          // true
console.log(isInt(1000000))      // true

// Floats
console.log(isInt(3.14))         // false
console.log(isInt(-2.5))         // false
console.log(isInt(1.0))          // false
console.log(isInt(0.0))          // false

// Strings
console.log(isInt('42'))         // false
console.log(isInt('3.14'))       // false
console.log(isInt(''))           // false

// Other types
console.log(isInt(null))         // false
console.log(isInt(undefined))    // false
console.log(isInt(true))         // false
console.log(isInt(false))        // false
console.log(isInt([]))           // false
console.log(isInt({}))           // false

Special Number Checking

typescript
import { isInt } from 'radash'

// NaN
console.log(isInt(NaN))          // false

// Infinity
console.log(isInt(Infinity))     // false
console.log(isInt(-Infinity))    // false

// Max/Min values
console.log(isInt(Number.MAX_VALUE))        // false
console.log(isInt(Number.MIN_VALUE))        // false
console.log(isInt(Number.MAX_SAFE_INTEGER)) // true
console.log(isInt(Number.MIN_SAFE_INTEGER)) // true

// Boundary values
console.log(isInt(Number.MAX_SAFE_INTEGER + 1)) // false
console.log(isInt(Number.MIN_SAFE_INTEGER - 1)) // false

Type Guard Usage

typescript
import { isInt } from 'radash'

function processNumber(value: unknown) {
  if (isInt(value)) {
    // TypeScript knows value is an integer
    console.log(`Processing integer: ${value}`)
    return value * 2
  }
  
  if (typeof value === 'number') {
    // Handle floats
    console.log(`Processing float: ${value}`)
    return Math.round(value * 2)
  }
  
  console.log('Not a number')
  return null
}

console.log(processNumber(42))    // Processing integer: 42 84
console.log(processNumber(3.14))  // Processing float: 3.14 6
console.log(processNumber('abc')) // Not a number null

Array Filtering

typescript
import { isInt } from 'radash'

const mixedArray = [1, 2.5, 3, 4.7, '5', 6.0, 7, 8.9, null, undefined]

const integers = mixedArray.filter(isInt)
console.log(integers) // [1, 3, 7]

const nonIntegers = mixedArray.filter(item => !isInt(item))
console.log(nonIntegers) // [2.5, 4.7, '5', 6.0, 8.9, null, undefined]

Object Property Checking

typescript
import { isInt } from 'radash'

const data = {
  id: 1,
  price: 19.99,
  quantity: 5,
  rating: 4.5,
  score: 100,
  weight: 2.5,
  isAvailable: true
}

const integerProperties = Object.entries(data)
  .filter(([key, value]) => isInt(value))
  .map(([key, value]) => ({ key, value }))

console.log(integerProperties)
// [
//   { key: 'id', value: 1 },
//   { key: 'quantity', value: 5 },
//   { key: 'score', value: 100 }
// ]

Form Validation

typescript
import { isInt } from 'radash'

interface FormData {
  age: unknown
  quantity: unknown
  price: unknown
  score: unknown
}

function validateForm(data: FormData) {
  const errors: string[] = []
  
  if (!isInt(data.age)) {
    errors.push('Age must be a whole number')
  }
  
  if (!isInt(data.quantity)) {
    errors.push('Quantity must be a whole number')
  }
  
  if (typeof data.price !== 'number') {
    errors.push('Price must be a number')
  }
  
  if (!isInt(data.score)) {
    errors.push('Score must be a whole number')
  }
  
  return errors
}

console.log(validateForm({
  age: 25,
  quantity: 5,
  price: 19.99,
  score: 85
})) // []

console.log(validateForm({
  age: 25.5,
  quantity: '5',
  price: 19.99,
  score: 85.5
})) // ['Age must be a whole number', 'Quantity must be a whole number', 'Score must be a whole number']

API Response Processing

typescript
import { isInt } from 'radash'

interface ApiResponse {
  id: number
  count: unknown
  price: unknown
  rating: unknown
}

function processApiResponse(response: ApiResponse) {
  const processed = {
    id: response.id,
    count: isInt(response.count) ? response.count : 0,
    price: typeof response.price === 'number' ? response.price : 0,
    rating: typeof response.rating === 'number' ? response.rating : 0
  }
  
  return processed
}

const response1: ApiResponse = {
  id: 1,
  count: 5,
  price: 19.99,
  rating: 4.5
}

const response2: ApiResponse = {
  id: 2,
  count: '5',
  price: '19.99',
  rating: null
}

console.log(processApiResponse(response1))
// { id: 1, count: 5, price: 19.99, rating: 4.5 }

console.log(processApiResponse(response2))
// { id: 2, count: 0, price: 0, rating: 0 }

Mathematical Calculations

typescript
import { isInt } from 'radash'

function calculateFactorial(value: unknown): number {
  if (!isInt(value) || value < 0) {
    return 0
  }
  
  let result = 1
  for (let i = 2; i <= value; i++) {
    result *= i
  }
  return result
}

function calculateDivisors(value: unknown): number[] {
  if (!isInt(value) || value <= 0) {
    return []
  }
  
  const divisors: number[] = []
  for (let i = 1; i <= value; i++) {
    if (value % i === 0) {
      divisors.push(i)
    }
  }
  return divisors
}

console.log(calculateFactorial(5))     // 120
console.log(calculateFactorial(3.14))  // 0
console.log(calculateDivisors(12))     // [1, 2, 3, 4, 6, 12]
console.log(calculateDivisors(3.5))    // []

Database Query Result Processing

typescript
import { isInt } from 'radash'

interface DatabaseRecord {
  id: number
  quantity: unknown
  price: unknown
  discount: unknown
}

function sanitizeDatabaseRecord(record: DatabaseRecord) {
  return {
    id: record.id,
    quantity: isInt(record.quantity) ? record.quantity : 0,
    price: typeof record.price === 'number' ? record.price : 0,
    discount: typeof record.discount === 'number' ? record.discount : 0
  }
}

const dbRecord: DatabaseRecord = {
  id: 1,
  quantity: 10,
  price: 29.99,
  discount: 5
}

console.log(sanitizeDatabaseRecord(dbRecord))
// { id: 1, quantity: 10, price: 29.99, discount: 5 }

Configuration File Processing

typescript
import { isInt } from 'radash'

interface Config {
  port: unknown
  maxConnections: unknown
  timeout: unknown
  retries: unknown
}

function validateConfig(config: Config) {
  const errors: string[] = []
  
  if (!isInt(config.port)) {
    errors.push('port must be a whole number')
  }
  
  if (!isInt(config.maxConnections)) {
    errors.push('maxConnections must be a whole number')
  }
  
  if (typeof config.timeout !== 'number') {
    errors.push('timeout must be a number')
  }
  
  if (!isInt(config.retries)) {
    errors.push('retries must be a whole number')
  }
  
  return errors
}

const validConfig: Config = {
  port: 3000,
  maxConnections: 10,
  timeout: 5000.5,
  retries: 3
}

const invalidConfig: Config = {
  port: '3000',
  maxConnections: 10.5,
  timeout: '5000ms',
  retries: 3.2
}

console.log(validateConfig(validConfig))   // []
console.log(validateConfig(invalidConfig)) // ['port must be a whole number', 'maxConnections must be a whole number', 'timeout must be a number', 'retries must be a whole number']

Game Development

typescript
import { isInt } from 'radash'

interface PlayerStats {
  level: unknown
  health: unknown
  mana: unknown
  experience: unknown
}

function validatePlayerStats(stats: PlayerStats) {
  const validStats: Partial<PlayerStats> = {}
  
  if (isInt(stats.level)) {
    validStats.level = stats.level
  }
  
  if (isInt(stats.health)) {
    validStats.health = stats.health
  }
  
  if (isInt(stats.mana)) {
    validStats.mana = stats.mana
  }
  
  if (isInt(stats.experience)) {
    validStats.experience = stats.experience
  }
  
  return validStats
}

const playerStats: PlayerStats = {
  level: 10,
  health: 100,
  mana: 50,
  experience: 1250
}

console.log(validatePlayerStats(playerStats))
// { level: 10, health: 100, mana: 50, experience: 1250 }

Financial Calculations

typescript
import { isInt } from 'radash'

interface FinancialData {
  principal: unknown
  years: unknown
  rate: unknown
  payments: unknown
}

function calculateSimpleInterest(data: FinancialData): number {
  if (!isInt(data.years) || !isInt(data.payments)) {
    return 0
  }
  
  if (typeof data.principal !== 'number' || typeof data.rate !== 'number') {
    return 0
  }
  
  return data.principal * data.rate * data.years
}

function validateFinancialData(data: FinancialData) {
  const errors: string[] = []
  
  if (typeof data.principal !== 'number') {
    errors.push('Principal must be a number')
  }
  
  if (!isInt(data.years)) {
    errors.push('Years must be a whole number')
  }
  
  if (typeof data.rate !== 'number') {
    errors.push('Rate must be a number')
  }
  
  if (!isInt(data.payments)) {
    errors.push('Payments must be a whole number')
  }
  
  return errors
}

const loanData: FinancialData = {
  principal: 10000,
  years: 5,
  rate: 0.05,
  payments: 12
}

console.log(calculateSimpleInterest(loanData)) // 2500
console.log(validateFinancialData(loanData))   // []

Scientific Calculations

typescript
import { isInt } from 'radash'

function isPrime(value: unknown): boolean {
  if (!isInt(value) || value < 2) {
    return false
  }
  
  for (let i = 2; i <= Math.sqrt(value); i++) {
    if (value % i === 0) {
      return false
    }
  }
  return true
}

function getPrimeFactors(value: unknown): number[] {
  if (!isInt(value) || value < 2) {
    return []
  }
  
  const factors: number[] = []
  let n = value
  
  for (let i = 2; i <= Math.sqrt(n); i++) {
    while (n % i === 0) {
      factors.push(i)
      n /= i
    }
  }
  
  if (n > 1) {
    factors.push(n)
  }
  
  return factors
}

console.log(isPrime(17))           // true
console.log(isPrime(15))           // false
console.log(isPrime(3.14))         // false
console.log(getPrimeFactors(12))   // [2, 2, 3]
console.log(getPrimeFactors(3.5))  // []

Array Processing

typescript
import { isInt } from 'radash'

function findIntegers(array: unknown[]): number[] {
  return array.filter(isInt)
}

function calculateIntegerStats(array: unknown[]) {
  const integers = findIntegers(array)
  
  if (integers.length === 0) {
    return { count: 0, sum: 0, average: 0, min: null, max: null }
  }
  
  return {
    count: integers.length,
    sum: integers.reduce((sum, val) => sum + val, 0),
    average: integers.reduce((sum, val) => sum + val, 0) / integers.length,
    min: Math.min(...integers),
    max: Math.max(...integers)
  }
}

const mixedArray = [1, 2.5, 3, 4.7, '5', 6, 7.8, 8, 9.1, 10]

console.log(findIntegers(mixedArray)) // [1, 3, 6, 8, 10]
console.log(calculateIntegerStats(mixedArray))
// { count: 5, sum: 28, average: 5.6, min: 1, max: 10 }

Boundary Value Testing

typescript
import { isInt } from 'radash'

// Test boundary values
const boundaryTests = [
  Number.MAX_SAFE_INTEGER,
  Number.MIN_SAFE_INTEGER,
  Number.MAX_SAFE_INTEGER + 1,
  Number.MIN_SAFE_INTEGER - 1,
  0,
  -0,
  1,
  -1,
  1.0,
  -1.0,
  1.1,
  -1.1
]

boundaryTests.forEach(value => {
  console.log(`${value} is integer: ${isInt(value)}`)
})
// 9007199254740991 is integer: true
// -9007199254740991 is integer: true
// 9007199254740992 is integer: false
// -9007199254740992 is integer: false
// 0 is integer: true
// 0 is integer: true
// 1 is integer: true
// -1 is integer: true
// 1 is integer: true
// -1 is integer: true
// 1.1 is integer: false
// -1.1 is integer: false

Performance Testing

typescript
import { isInt } from 'radash'

function benchmarkIsInt() {
  const testValues = [
    1, 2, 3, 4, 5,
    1.1, 2.2, 3.3, 4.4, 5.5,
    '1', '2', '3', '4', '5',
    null, undefined, true, false,
    [], {}, () => {}
  ]
  
  const iterations = 1000000
  const start = performance.now()
  
  for (let i = 0; i < iterations; i++) {
    testValues.forEach(value => {
      isInt(value)
    })
  }
  
  const end = performance.now()
  console.log(`Benchmark completed in ${end - start}ms`)
}

// benchmarkIsInt() // Run performance test

Notes

  1. Integer Definition: Only checks for true integers, excludes floats
  2. Safe Integers: Values beyond safe integer range return false
  3. Type Guards: Serves as a TypeScript type guard
  4. Performance: Fast checking, suitable for high-frequency use
  5. Boundary Values: Correctly handles 0, negative numbers, max/min safe integers

Differences from Other Methods

  • isInt(): Checks if value is an integer
  • Number.isInteger(): Native JavaScript method
  • isNumber(): Checks if value is a number (including floats)
  • Number.isSafeInteger(): Checks if value is a safe integer

Practical Application Scenarios

  1. Form Validation: Validate user input as integers
  2. API Processing: Handle integer fields in API responses
  3. Database Operations: Validate database field types
  4. Mathematical Calculations: Ensure calculation parameters are integers
  5. Game Development: Handle integer values in games
  6. Financial Applications: Handle currency and quantity calculations

Released under the MIT License.