Skip to content

Type & Data

The Type Module provides precise type detection and an enhanced library of operations for JavaScript's four basic data types (Number, String, Array, Object).

It not only compensates for the limitations of the native typeof but also encapsulates high-frequency business logic such as deep cloning, deep merging, and random data generation.

Import Method

javascript
import { tType, tNum, tStr, tArr, tObj } from "@techui/utils";

Type Recognition

tType(data) is a precise type detection function implemented based on Object.prototype.toString, which resolves native flaws such as typeof null === 'object'.

  • Returns: A lowercase type string (e.g., 'string', 'number', 'array', 'object', 'date', 'regexp').
javascript
tType([]); // "array"
tType(null); // "null"
tType(new Date()); // "date"

Number Utilities

tNum provides number validation, random number generation, and formatting capabilities.

Validation & Judgment

  • verify(num): Determines if it is a number type.
  • isNEG0(num): Determines if it is (Equal Greater 0).
  • isNG0(num): Determines if it is (Greater 0).
  • isValidNumber(str): Determines if a string is a valid number (supports decimals).
  • isNumberWithCommas(str): Determines if it is a number format with thousands separators (e.g., 1,234.56).

Randomness & Calculation

  • rdm(min, max): Generates a random integer within a specified range.
  • safeFixed(num, decimal): Safely rounds to a specified number of decimal places (fixes JS floating-point precision issues).
javascript
const money = tNum.safeFixed(0.1 + 0.2, 1); // 0.3
const randomScore = tNum.rdm(60, 100);

Conversion & Formatting

  • convert(str, precision): Safely converts a string to a number.
    • Returns a { success: boolean, num?: number, error?: string } structure and does not throw exceptions.
  • padZero(val, len): Pads a number with zeros (e.g., 5 -> "5.00").
javascript
const res = tNum.convert("12.345", 2);
if (res.success) {
  console.log(res.num); // 12.35
}

String Utilities

tStr focuses on string generation and case conversion.

  • rdm(len): Generates a random string of a specified length (excludes easily confused characters such as I, l, 1, O, 0), often used for temporary IDs or verification codes.
  • upper1st(str): Capitalizes the first letter.
javascript
const id = tStr.rdm(8); // "aBcdEfGh"
const title = tStr.upper1st("techUI"); // "TechUI"

Array Utilities

tArr provides array validation, comparison, and random picking.

Field Validation

fieldValid(arr, fields): Checks if objects in an array contain the specified fields. This is very useful when processing list data returned by APIs to quickly locate defective data.

javascript
const users = [{ id: 1, name: 'A' }, { id: 2 }]; // Second item missing name
const check = tArr.fieldValid(users, ['id', 'name']);

if (!check.valid) {
  console.error(check.message); 
  // "Item at index 1 is missing field "name"..."
}

Other Methods

  • rdmpk1(arr): Randomly picks one item from an array (Random Pick 1).
  • shallowEQ(arr1, arr2): Shallow array comparison, used to determine if the contents of two simple arrays are identical.

Object Utilities

tObj is the core for handling complex business logic, covering deep cloning, deep merging, and key-value validation.

Deep Operations (Deep Ops)

  • dpc(obj): Deep Clone. Implemented based on JSON, suitable for pure data objects without functions or regex.
  • dpm(target, merged): Deep Merge. Recursively merges two objects, used for handling configuration overrides.
  • isEq(val1, val2): Deep Equality Judgment. Supports recursive comparison of objects, arrays, dates, and regex.
javascript
const defaultCfg = { theme: { color: 'red', size: 10 } };
const userCfg = { theme: { color: 'blue' } };

// Deep merge: preserves size: 10
const finalCfg = tObj.dpm(defaultCfg, userCfg); 
// { theme: { color: 'blue', size: 10 } }

Key-Value Validation

keyValid(obj, keys, all): Checks if an object contains specified keys.

  • all=true: Must contain all specified keys.
  • all=false: Valid if it contains any one of the specified keys.
javascript
const params = { keyword: 'test', page: 1 };
const valid = tObj.keyValid(params, ['keyword', 'page'], true);

Auxiliary Methods

  • isEmpty(obj): Determines if an object is empty {}.
  • pick(obj, keys): Extracts specified fields from an object and returns a new object.
  • remKey(obj, keyOrKeys): Removes specified fields from an object and returns a new object (does not modify the original object).

Released under the MIT License.