Skip to content
VersionSize

isPrimitive

Checks if a value is a primitive type (string, number, boolean, null, undefined, symbol, or bigint).

Implementation

View Source Code
ts
/**
 * Type guard to check if a value is a primitive
 *
 * @example
 * ```ts
 * isPrimitive('Hello World'); // true
 * isPrimitive(42); // true
 * isPrimitive(true); // true
 * isPrimitive({}); // false
 * isPrimitive([]); // false
 * isPrimitive(() => {}); // false
 * ```
 * @param arg - The argument to be checked.
 *
 * @returns `true` if the value is a primitive, else `false`.
 */
export function isPrimitive(arg: unknown): arg is string | number | boolean {
  const type = typeof arg;
  return type === 'string' || type === 'boolean' || (type === 'number' && !Number.isNaN(arg));
}

export const IS_PRIMITIVE_ERROR_MSG = 'Expected a primitive value';

Features

  • Comprehensive: Checks all JavaScript primitive types
  • Type Guard: Helps narrow types in TypeScript
  • Isomorphic: Works in both Browser and Node.js

API

ts
function isPrimitive(value: unknown): boolean;

Parameters

  • value: The value to check

Returns

  • true if the value is a primitive, false otherwise

Examples

Basic Usage

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

isPrimitive(42); // true
isPrimitive('foo'); // true
isPrimitive(true); // true
isPrimitive(null); // true
isPrimitive(undefined); // true
isPrimitive(Symbol('test')); // true
isPrimitive({}); // false
isPrimitive([]); // false

Filtering Primitives

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

const mixed = [1, 'hello', {}, null, [], true];
const primitives = mixed.filter(isPrimitive);
// [1, 'hello', null, true]

Implementation Notes

  • Covers all 7 primitive types: string, number, boolean, null, undefined, symbol, bigint
  • Returns false for objects, arrays, functions, and other reference types
  • Useful for distinguishing between primitive and reference types

See Also