Aller au contenu principal

isString()

isString(value): value is string

Checks if a value is a string.


Parameters

value: unknown

The value to check.


Returns: value is string

true if the value is a string, false otherwise.


Since

1.0.0


Example

isString('hello');       // => true
isString(''); // => true
isString(String(123)); // => true
isString(123); // => false
isString(null); // => false
isString(new String()); // => false (String object)

How it works?

Type guard that checks if a value is a string.

Type Narrowing

Common Checks

ValueResult
'hello' true
'' true
`template` true
String(123) true
new String('hello') false (boxed)
123 false
['h', 'i'] false

Use Cases

Validate text input 📌

Ensure a value is a string before manipulation. Essential for form handling and text processing.

if (isString(input)) {
const trimmed = input.trim();
saveToDatabase(trimmed);
}

Filter strings from mixed arrays

Extract string values from arrays containing mixed types.

const values = ["hello", 42, "world", null, true];
const strings = values.filter(isString);
// strings: string[] = ["hello", "world"]