Skip to content
VersionSize

isString

Checks if a value is a string.

Implementation

View Source Code
ts
/**
 * Determines if the passed value is a String.
 *
 * @example
 * ```ts
 * isString('Hello World'); // true
 * isString(42); // false
 * ```
 *
 * @param arg - The argument to be checked.
 *
 * @returns `true` if the value is a String, else `false`.
 */
export function isString(arg: unknown): arg is string {
  return typeof arg === 'string';
}

export const IS_STRING_ERROR_MSG = 'Expected a string';

Features

  • Type Guard: Narrows unknown to string
  • Isomorphic: Works in both Browser and Node.js

API

ts
function isString(value: unknown): value is string;

Parameters

  • value: The value to check

Returns

  • true if the value is a string, false otherwise

Examples

Basic Usage

ts
import { isString } from '@vielzeug/toolkit';

isString('foo'); // true
isString(42); // false
isString(''); // true
isString(String('hello')); // true

Type Guard Usage

ts
import { isString } from '@vielzeug/toolkit';

function process(value: unknown) {
  if (isString(value)) {
    // TypeScript knows value is string here
    return value.toUpperCase();
  }
  return 'Not a string';
}

Implementation Notes

  • Returns false for String objects created with new String()
  • Use this for primitive string type checking
  • Useful for validation and type narrowing in TypeScript

See Also