0
# String Type Validation
1
2
String type checking functions providing comprehensive string validation including empty/full string checks and specialized string format validation.
3
4
## Capabilities
5
6
### String Type Checking
7
8
Returns whether the payload is a string primitive.
9
10
```typescript { .api }
11
/**
12
* Returns whether the payload is a string
13
* @param payload - Value to check
14
* @returns Type guard indicating if payload is string
15
*/
16
function isString(payload: unknown): payload is string;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { isString } from "is-what";
23
24
isString("hello"); // true
25
isString(""); // true (empty string is still a string)
26
isString(`template ${1}`); // true
27
isString(String(123)); // true (converts to primitive string)
28
isString(new String("hello")); // false (String object, not primitive)
29
isString(123); // false
30
isString(null); // false
31
32
if (isString(input)) {
33
// TypeScript knows input is string
34
console.log(input.toUpperCase());
35
console.log(input.length);
36
}
37
```
38
39
### Empty String Checking
40
41
Returns whether the payload is an empty string ("").
42
43
```typescript { .api }
44
/**
45
* Returns whether the payload is an empty string
46
* @param payload - Value to check
47
* @returns Type guard indicating if payload is empty string
48
*/
49
function isEmptyString(payload: unknown): payload is "";
50
```
51
52
**Usage Examples:**
53
54
```typescript
55
import { isEmptyString } from "is-what";
56
57
isEmptyString(""); // true
58
isEmptyString("hello"); // false
59
isEmptyString(" "); // false (space is not empty)
60
isEmptyString(null); // false
61
isEmptyString(undefined); // false
62
63
// Validation pattern
64
function validateRequiredField(value: unknown, fieldName: string) {
65
if (isEmptyString(value)) {
66
throw new Error(`${fieldName} cannot be empty`);
67
}
68
69
if (!isString(value)) {
70
throw new Error(`${fieldName} must be a string`);
71
}
72
73
return value; // TypeScript knows this is a non-empty string
74
}
75
```
76
77
### Full String Checking
78
79
Returns whether the payload is a non-empty string.
80
81
```typescript { .api }
82
/**
83
* Returns whether the payload is a non-empty string
84
* @param payload - Value to check
85
* @returns Type guard indicating if payload is non-empty string
86
*/
87
function isFullString(payload: unknown): payload is string;
88
```
89
90
**Usage Examples:**
91
92
```typescript
93
import { isFullString } from "is-what";
94
95
isFullString("hello"); // true
96
isFullString("a"); // true
97
isFullString(" "); // true (space counts as content)
98
isFullString(""); // false
99
isFullString(null); // false
100
isFullString(123); // false
101
102
// Safe string operations
103
function processText(input: unknown) {
104
if (isFullString(input)) {
105
// Safe to perform string operations
106
return input.trim().toLowerCase();
107
}
108
return null;
109
}
110
111
// Form validation
112
function validateInput(userInput: unknown) {
113
if (!isFullString(userInput)) {
114
return { valid: false, error: "Input must be a non-empty string" };
115
}
116
117
return { valid: true, value: userInput };
118
}
119
```
120
121
### Hexadecimal String Validation
122
123
Returns whether the payload is a valid hexadecimal string. Optionally validates the string length.
124
125
```typescript { .api }
126
/**
127
* Checks if a string is a valid hexadecimal string. If a length is provided,
128
* it also checks that the string has that length.
129
* @param payload - Value to check
130
* @param length - Optional expected length of the hexadecimal string
131
* @returns Type guard indicating if payload is hexadecimal string
132
*/
133
function isHexDecimal(payload: unknown, length?: number): payload is string;
134
```
135
136
**Usage Examples:**
137
138
```typescript
139
import { isHexDecimal } from "is-what";
140
141
// Valid hexadecimal strings
142
isHexDecimal("FF"); // true
143
isHexDecimal("123ABC"); // true
144
isHexDecimal("deadbeef"); // true
145
isHexDecimal("ff00cc", 6); // true (length matches)
146
147
// Invalid hexadecimal strings
148
isHexDecimal("123G"); // false (G is not a hex digit)
149
isHexDecimal("hello"); // false
150
isHexDecimal(""); // false
151
isHexDecimal("ff00cc", 4); // false (length doesn't match)
152
isHexDecimal(255); // false (number, not string)
153
154
// Note: This function does NOT accept 0x prefix
155
isHexDecimal("0xFF"); // false (0x prefix not supported)
156
isHexDecimal("xFF"); // false (x prefix not supported)
157
158
// Practical usage
159
function parseHexColor(color: unknown) {
160
if (isHexDecimal(color)) {
161
// Safe to parse as hexadecimal
162
const normalized = color.startsWith('0x')
163
? color.slice(2)
164
: color.startsWith('#')
165
? color.slice(1)
166
: color;
167
168
return parseInt(normalized, 16);
169
}
170
171
throw new Error("Invalid hexadecimal color format");
172
}
173
174
// Validation for hex input
175
function validateHexInput(input: unknown) {
176
if (isHexDecimal(input)) {
177
return {
178
valid: true,
179
value: input,
180
decimal: parseInt(input.replace(/^0x/i, ''), 16)
181
};
182
}
183
184
return { valid: false, error: "Must be a valid hexadecimal string" };
185
}
186
```
187
188
## Combined String Validation Patterns
189
190
```typescript
191
import {
192
isString,
193
isEmptyString,
194
isFullString,
195
isHexDecimal
196
} from "is-what";
197
198
function analyzeString(value: unknown) {
199
if (!isString(value)) {
200
return "Not a string";
201
}
202
203
if (isEmptyString(value)) {
204
return "Empty string";
205
}
206
207
const analysis = [`String with ${value.length} characters`];
208
209
if (isHexDecimal(value)) {
210
analysis.push("valid hexadecimal");
211
}
212
213
return analysis.join(", ");
214
}
215
216
// String processing pipeline
217
function processStringInput(input: unknown) {
218
// Basic string validation
219
if (!isString(input)) {
220
throw new Error("Input must be a string");
221
}
222
223
// Handle empty string
224
if (isEmptyString(input)) {
225
return { processed: "", warnings: ["Empty string provided"] };
226
}
227
228
// Process non-empty strings
229
const processed = input.trim();
230
const warnings = [];
231
232
if (processed !== input) {
233
warnings.push("Whitespace was trimmed");
234
}
235
236
// Check for special formats
237
const metadata: any = {};
238
if (isHexDecimal(processed)) {
239
metadata.hexValue = parseInt(processed.replace(/^0x/i, ''), 16);
240
metadata.format = "hexadecimal";
241
}
242
243
return {
244
processed,
245
original: input,
246
warnings,
247
metadata
248
};
249
}
250
251
// Safe string utilities
252
function safeStringOperations(text: unknown) {
253
if (isFullString(text)) {
254
return {
255
uppercase: text.toUpperCase(),
256
lowercase: text.toLowerCase(),
257
length: text.length,
258
words: text.split(/\s+/).filter(word => word.length > 0),
259
isEmpty: false
260
};
261
}
262
263
if (isEmptyString(text)) {
264
return {
265
uppercase: "",
266
lowercase: "",
267
length: 0,
268
words: [],
269
isEmpty: true
270
};
271
}
272
273
return null; // Not a string
274
}
275
276
// Example usage
277
analyzeString("ff00cc"); // "String with 6 characters, valid hexadecimal"
278
analyzeString(""); // "Empty string"
279
analyzeString("hello world"); // "String with 11 characters"
280
analyzeString(123); // "Not a string"
281
282
const result = processStringInput(" 0xFF ");
283
// Returns: {
284
// processed: "0xFF",
285
// original: " 0xFF ",
286
// warnings: ["Whitespace was trimmed"],
287
// metadata: { hexValue: 255, format: "hexadecimal" }
288
// }
289
```