-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredicates.ts
More file actions
62 lines (59 loc) · 1.96 KB
/
predicates.ts
File metadata and controls
62 lines (59 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* @fileoverview String predicates: `isBlankString` and
* `isNonEmptyString`. Both are TypeScript type guards so callers can
* narrow `unknown` → `string` (or `BlankString` / non-empty string)
* without an extra cast.
*/
import type { BlankString, EmptyString } from './types'
/**
* Check if a value is a blank string (empty or only whitespace).
*
* A blank string is defined as a string that is either:
* - Completely empty (length 0)
* - Contains only whitespace characters (spaces, tabs, newlines, etc.)
*
* This is useful for validation when you need to ensure user input
* contains actual content, not just whitespace.
*
* @param value - The value to check
* @returns `true` if the value is a blank string, `false` otherwise
*
* @example
* ```ts
* isBlankString('') // true
* isBlankString(' ') // true
* isBlankString('\n\t ') // true
* isBlankString('hello') // false
* isBlankString(null) // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isBlankString(value: unknown): value is BlankString {
return typeof value === 'string' && (!value.length || /^\s+$/.test(value))
}
/**
* Check if a value is a non-empty string.
*
* Returns `true` only if the value is a string with at least one character.
* This includes strings containing only whitespace (use `isBlankString()` if
* you want to exclude those). Type guard ensures TypeScript knows the value
* is a string after this check.
*
* @param value - The value to check
* @returns `true` if the value is a non-empty string, `false` otherwise
*
* @example
* ```ts
* isNonEmptyString('hello') // true
* isNonEmptyString(' ') // true (contains whitespace)
* isNonEmptyString('') // false
* isNonEmptyString(null) // false
* isNonEmptyString(123) // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isNonEmptyString(
value: unknown,
): value is Exclude<string, EmptyString> {
return typeof value === 'string' && value.length > 0
}