Custom type guards for runtime type checking
1// Basic type guard
2function isString(value: unknown): value is string {
3 return typeof value === 'string';
4}
5
6// Type guard for objects
7interface User {
8 id: string;
9 name: string;
10 email: string;
11}
12
13function isUser(obj: unknown): obj is User {
14 return (
15 typeof obj === 'object' &&
16 obj !== null &&
17 'id' in obj &&
18 'name' in obj &&
19 'email' in obj &&
20 typeof (obj as User).id === 'string' &&
21 typeof (obj as User).name === 'string' &&
22 typeof (obj as User).email === 'string'
23 );
24}
25
26// Type guard for arrays
27function isStringArray(value: unknown): value is string[] {
28 return Array.isArray(value) && value.every(item => typeof item === 'string');
29}
30
31// Generic type guard for arrays
32function isArrayOf<T>(
33 value: unknown,
34 guard: (item: unknown) => item is T
35): value is T[] {
36 return Array.isArray(value) && value.every(guard);
37}
38
39// Usage examples
40const data: unknown = { id: '1', name: 'John', email: 'john@example.com' };
41
42if (isUser(data)) {
43 console.log(data.name); // TypeScript knows data is User
44}
45
46const items: unknown = ['a', 'b', 'c'];
47
48if (isArrayOf(items, isString)) {
49 console.log(items.join(', ')); // TypeScript knows items is string[]
50}Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.