Packages@accelint/predicates
isString
Type guard that determines if a value is a string (primitive or String object)
Type guard that determines if a value is a string, including both primitive strings and String object instances.
Usage
import { isString } from '@accelint/predicates/is-string';
isString('hello'); // true
isString(new String('hi')); // true
isString(123); // false
isString(null); // falseReference
function isString(val: unknown): val is stringParameters
| Parameter | Type | Description |
|---|---|---|
val | unknown | Value to check |
Returns
Type guard that narrows the type to string. Returns true for both primitive strings and String object instances.
Examples
Example: Type narrowing for string operations
import { isString } from '@accelint/predicates/is-string';
function processValue(val: unknown) {
if (isString(val)) {
// TypeScript knows val is string here
return val.toUpperCase();
}
throw new Error('Expected string');
}
processValue('hello'); // "HELLO"
processValue(new String('hi')); // "HI"
processValue(123); // Error: Expected stringExample: Filtering mixed arrays
import { isString } from '@accelint/predicates/is-string';
const mixed = ['hello', 42, 'world', null, undefined, true, 'test'];
const strings = mixed.filter(isString);
// ['hello', 'world', 'test']Example: Safe string concatenation
import { isString } from '@accelint/predicates/is-string';
function safeConcat(...values: unknown[]): string {
const strings = values.filter(isString);
return strings.join(' ');
}
safeConcat('Hello', 'world', 123, null, '!');
// "Hello world !"Example: Validating object properties
import { isString } from '@accelint/predicates/is-string';
interface Config {
name: unknown;
path: unknown;
}
function validateConfig(config: Config): config is { name: string; path: string } {
return isString(config.name) && isString(config.path);
}
const config = { name: 'app', path: '/home/user' };
if (validateConfig(config)) {
// TypeScript knows name and path are strings
console.log(config.name.toUpperCase());
}Good to know: This predicate returns
truefor bothtypeof val === 'string'(primitive) andval instanceof String(object wrapper). Most JavaScript code uses primitive strings, but this predicate handles both cases.
Related
- isNumber - Type guard for number values
- isNothing - Check for null or undefined values
- isSomething - Check for non-null/undefined values