Skip to content

isString

Checks if a value is a string type.

Basic Usage

typescript
import { isString } from 'radash'

console.log(isString('hello'))        // true
console.log(isString(''))             // true
console.log(isString(123))            // false
console.log(isString(true))           // false
console.log(isString(null))           // false

Syntax

typescript
function isString(value: any): value is string

Parameters

  • value (any): The value to check

Return Value

Returns a boolean value indicating whether the value is a string type. This is a type guard function.

Examples

Basic String Checking

typescript
import { isString } from 'radash'

// Normal strings
console.log(isString('hello'))        // true
console.log(isString('world'))        // true
console.log(isString('123'))          // true
console.log(isString('true'))         // true

// Empty strings
console.log(isString(''))             // true
console.log(isString('   '))          // true

// Special strings
console.log(isString('Hello World'))  // true
console.log(isString('你好'))          // true
console.log(isString('123.45'))       // true

Handling Other Types

typescript
import { isString } from 'radash'

// Numbers
console.log(isString(123))            // false
console.log(isString(3.14))           // false
console.log(isString(0))              // false
console.log(isString(NaN))            // false

// Booleans
console.log(isString(true))           // false
console.log(isString(false))          // false

// null and undefined
console.log(isString(null))           // false
console.log(isString(undefined))      // false

// Objects and arrays
console.log(isString({}))             // false
console.log(isString([]))             // false
console.log(isString({ name: 'Alice' })) // false

// Functions
console.log(isString(() => {}))       // false
console.log(isString(function() {}))  // false

// Symbol
console.log(isString(Symbol()))       // false

Type Guard Usage

typescript
import { isString } from 'radash'

function processValue(value: unknown) {
  if (isString(value)) {
    // TypeScript knows value is a string type
    return value.toUpperCase()
  }
  
  return String(value)
}

console.log(processValue('hello'))    // HELLO
console.log(processValue(123))        // 123
console.log(processValue(true))       // true

Array Filtering

typescript
import { isString } from 'radash'

const mixedArray = ['hello', 123, 'world', true, '', null, 'test']

const strings = mixedArray.filter(isString)
console.log(strings) // ['hello', 'world', '', 'test']

const nonStrings = mixedArray.filter(item => !isString(item))
console.log(nonStrings) // [123, true, null]

Form Validation

typescript
import { isString } from 'radash'

function validateForm(data: Record<string, any>) {
  const errors: string[] = []
  
  if (!isString(data.name) || data.name.trim() === '') {
    errors.push('Name must be a non-empty string')
  }
  
  if (!isString(data.email) || !data.email.includes('@')) {
    errors.push('Email must be a valid string')
  }
  
  if (isString(data.age)) {
    errors.push('Age must be a number, not a string')
  }
  
  return errors
}

const formData = {
  name: 'Alice',
  email: 'alice@example.com',
  age: 25
}

const errors = validateForm(formData)
console.log(errors) // ['Age must be a number, not a string']

String Processing

typescript
import { isString } from 'radash'

function processStrings(items: any[]) {
  return items
    .filter(isString)
    .map(str => str.trim())
    .filter(str => str.length > 0)
}

const data = ['  hello  ', 123, '  world  ', '', '  test  ', null]

const processed = processStrings(data)
console.log(processed) // ['hello', 'world', 'test']

Configuration Validation

typescript
import { isString } from 'radash'

class ConfigValidator {
  static validateStringConfig(config: Record<string, any>, key: string): boolean {
    const value = config[key]
    
    if (!isString(value)) {
      console.error(`Config key "${key}" must be a string`)
      return false
    }
    
    if (value.trim() === '') {
      console.error(`Config key "${key}" cannot be empty`)
      return false
    }
    
    return true
  }
  
  static getStringValues(config: Record<string, any>): string[] {
    return Object.values(config).filter(isString)
  }
}

const config = {
  apiUrl: 'https://api.example.com',
  timeout: 5000,
  apiKey: 'secret-key',
  debug: true
}

console.log(ConfigValidator.validateStringConfig(config, 'apiUrl'))    // true
console.log(ConfigValidator.validateStringConfig(config, 'timeout'))   // false
console.log(ConfigValidator.getStringValues(config))                   // ['https://api.example.com', 'secret-key']

Data Transformation

typescript
import { isString } from 'radash'

function transformData(data: any[]): any[] {
  return data.map(item => {
    if (isString(item)) {
      // Process string items
      return item.toUpperCase()
    } else if (typeof item === 'number') {
      // Process number items
      return item * 2
    } else {
      // Keep other types as is
      return item
    }
  })
}

const input = ['hello', 123, 'world', 456, true, null]
const output = transformData(input)

console.log(output) // ['HELLO', 246, 'WORLD', 912, true, null]

API Response Handling

typescript
import { isString } from 'radash'

function processApiResponse(response: any) {
  const result: any = {}
  
  for (const [key, value] of Object.entries(response)) {
    if (isString(value)) {
      // Process string values
      result[key] = value.trim()
    } else if (typeof value === 'number') {
      // Process number values
      result[key] = Math.round(value)
    } else {
      // Keep other types as is
      result[key] = value
    }
  }
  
  return result
}

const apiResponse = {
  name: '  Alice  ',
  age: 25.7,
  email: 'alice@example.com',
  active: true,
  score: 95.8
}

const processed = processApiResponse(apiResponse)
console.log(processed)
// {
//   name: 'Alice',
//   age: 26,
//   email: 'alice@example.com',
//   active: true,
//   score: 96
// }

Template Processing

typescript
import { isString } from 'radash'

function processTemplate(template: any, data: Record<string, any>): string {
  if (!isString(template)) {
    throw new Error('Template must be a string')
  }
  
  return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
    const value = data[key]
    return isString(value) ? value : String(value || '')
  })
}

const template = 'Hello {{name}}, you are {{age}} years old'
const data = {
  name: 'Alice',
  age: 25
}

const result = processTemplate(template, data)
console.log(result) // 'Hello Alice, you are 25 years old'

Input Sanitization

typescript
import { isString } from 'radash'

function sanitizeInput(input: any): string {
  if (!isString(input)) {
    return ''
  }
  
  return input
    .trim()
    .replace(/[<>]/g, '') // Remove potential HTML tags
    .slice(0, 100) // Limit length
}

console.log(sanitizeInput('  <script>alert("xss")</script>  ')) // 'scriptalert("xss")'
console.log(sanitizeInput(123)) // ''
console.log(sanitizeInput('  hello world  ')) // 'hello world'

Performance Testing

typescript
import { isString } from 'radash'

function benchmarkIsString() {
  const testValues = [
    'hello',
    'world',
    '123',
    '',
    '   ',
    123,
    true,
    null,
    undefined,
    {},
    [],
    () => {}
  ]
  
  const iterations = 1000000
  const start = performance.now()
  
  for (let i = 0; i < iterations; i++) {
    testValues.forEach(value => {
      isString(value)
    })
  }
  
  const end = performance.now()
  console.log(`Benchmark completed in ${end - start}ms`)
}

// benchmarkIsString() // Run performance test

Boundary Value Testing

typescript
import { isString } from 'radash'

// Test boundary values
const boundaryTests = [
  // String types
  '',
  ' ',
  'hello',
  '123',
  'true',
  'false',
  'null',
  'undefined',
  'Hello World',
  '你好',
  '123.45',
  '0',
  'NaN',
  'Infinity',
  '-Infinity',
  
  // Non-string types
  123,
  3.14,
  0,
  NaN,
  Infinity,
  -Infinity,
  true,
  false,
  null,
  undefined,
  {},
  [],
  () => {},
  Symbol(),
  new String('hello')
]

boundaryTests.forEach(value => {
  console.log(`${typeof value} ${String(value).slice(0, 20)}: ${isString(value)}`)
})

Notes

  1. String Detection: Accurately detects true string types
  2. Type Guard: Acts as a TypeScript type guard
  3. Performance: Fast checking speed, suitable for high-frequency use
  4. Boundary Values: Correctly handles all boundary cases
  5. String Objects: Returns false for String objects (not primitive strings)

Differences from Other Methods

  • isString(): Checks if value is a string type
  • typeof value === 'string': Native JavaScript check
  • value instanceof String: Checks for String objects (not primitive strings)
  • Object.prototype.toString.call(value) === '[object String]': Complex but accurate

Real-world Application Scenarios

  1. Form Validation: Validating user input as strings
  2. API Processing: Handling string responses from APIs
  3. Data Transformation: Processing string data in data pipelines
  4. Template Processing: Handling string templates
  5. Input Sanitization: Cleaning and validating string inputs
  6. Configuration Management: Validating string configuration values
  7. Configuration Validation: Validating string settings in configuration files

Released under the MIT License.