-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypescript-utility-types-guide.html
More file actions
843 lines (680 loc) · 40.9 KB
/
typescript-utility-types-guide.html
File metadata and controls
843 lines (680 loc) · 40.9 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TypeScript Utility Types: Complete Guide with Examples | DevToolbox Blog</title>
<meta name="description" content="Master TypeScript utility types: Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract, ReturnType, Parameters, and more. Practical examples and custom utility types.">
<meta name="keywords" content="typescript utility types, typescript partial, typescript pick, typescript omit, typescript record, typescript exclude, typescript mapped types, typescript conditional types">
<meta property="og:title" content="TypeScript Utility Types: Complete Guide with Examples">
<meta property="og:description" content="Master TypeScript utility types: Partial, Required, Pick, Omit, Record, Exclude, ReturnType, and custom utility types with examples.">
<meta property="og:type" content="article">
<meta property="og:url" content="https://devtoolbox.dedyn.io/blog/typescript-utility-types-guide">
<meta property="og:site_name" content="DevToolbox">
<meta property="og:image" content="https://devtoolbox.dedyn.io/og/blog-typescript-utility-types-guide.png">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="TypeScript Utility Types: Complete Guide with Examples">
<meta name="twitter:description" content="Master TypeScript utility types with practical examples.">
<meta property="article:published_time" content="2026-02-12">
<meta name="robots" content="index, follow">
<link rel="canonical" href="https://devtoolbox.dedyn.io/blog/typescript-utility-types-guide">
<link rel="icon" href="/favicon.ico" sizes="any">
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/icons/icon-192.png">
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#3b82f6">
<link rel="stylesheet" href="/css/style.css">
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"headline": "TypeScript Utility Types: Complete Guide with Examples",
"description": "Master TypeScript utility types: Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract, ReturnType, Parameters, and more. Practical examples and custom utility types.",
"datePublished": "2026-02-12",
"dateModified": "2026-02-12",
"url": "https://devtoolbox.dedyn.io/blog/typescript-utility-types-guide",
"author": { "@type": "Organization", "name": "DevToolbox" },
"publisher": { "@type": "Organization", "name": "DevToolbox", "logo": { "@type": "ImageObject", "url": "https://devtoolbox.dedyn.io/favicon.svg" } }
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "What are TypeScript utility types?",
"acceptedAnswer": { "@type": "Answer", "text": "TypeScript utility types are built-in generic types that transform existing types into new ones. They let you make properties optional (Partial), required (Required), read-only (Readonly), pick specific properties (Pick), omit properties (Omit), create dictionaries (Record), and extract or exclude union members (Extract, Exclude). They eliminate repetitive type definitions and keep your codebase DRY." }
},
{
"@type": "Question",
"name": "What is the difference between Pick and Omit in TypeScript?",
"acceptedAnswer": { "@type": "Answer", "text": "Pick<T, K> creates a new type by selecting specific properties K from type T, while Omit<T, K> creates a new type by removing properties K from type T. They are complementary: Pick is better when you want a small subset of properties, and Omit is better when you want most properties but need to exclude a few. For example, Pick<User, 'name' | 'email'> keeps only name and email, while Omit<User, 'password'> keeps everything except password." }
},
{
"@type": "Question",
"name": "How do I create custom utility types in TypeScript?",
"acceptedAnswer": { "@type": "Answer", "text": "Custom utility types are built using mapped types, conditional types, and the infer keyword. A mapped type iterates over keys of a type using the [K in keyof T] syntax and transforms each property. Conditional types use the T extends U ? X : Y pattern to branch based on type relationships. The infer keyword extracts types from within other types. For example, type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] } makes all nested properties optional." }
},
{
"@type": "Question",
"name": "When should I use Record vs a regular interface in TypeScript?",
"acceptedAnswer": { "@type": "Answer", "text": "Use Record<K, V> when you need a dictionary or map-like structure where all values share the same type, especially with dynamic or union keys. Use an interface when each property has a different type or when you need declaration merging. For example, Record<string, number> is ideal for a scores dictionary, while an interface is better for a User object with name (string), age (number), and active (boolean) properties." }
},
{
"@type": "Question",
"name": "What is the Awaited utility type in TypeScript?",
"acceptedAnswer": { "@type": "Answer", "text": "Awaited<T> (TypeScript 4.5+) recursively unwraps Promise types to get the resolved value type. Awaited<Promise<string>> gives you string, and Awaited<Promise<Promise<number>>> gives you number. It is especially useful with ReturnType when working with async functions: type Result = Awaited<ReturnType<typeof fetchUser>> gives you the resolved return type of an async function rather than a Promise." }
}
]
}
</script>
</head>
<body>
<header>
<nav>
<a href="/" class="logo"><span class="logo-icon">{ }</span><span>DevToolbox</span></a>
<div class="nav-links"><a href="/index.html#tools">Tools</a><a href="/index.html#cheat-sheets">Cheat Sheets</a><a href="/index.html#guides">Blog</a></div>
</nav>
</header>
<nav class="breadcrumb" aria-label="Breadcrumb"><a href="/">Home</a><span class="separator">/</span><a href="/index.html#guides">Blog</a><span class="separator">/</span><span class="current">TypeScript Utility Types Guide</span></nav>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{ "@type": "ListItem", "position": 1, "name": "Home", "item": "https://devtoolbox.dedyn.io/" },
{ "@type": "ListItem", "position": 2, "name": "Blog", "item": "https://devtoolbox.dedyn.io/blog" },
{ "@type": "ListItem", "position": 3, "name": "TypeScript Utility Types Guide" }
]
}
</script>
<main class="blog-post">
<article>
<h1>TypeScript Utility Types: Complete Guide with Examples</h1>
<p class="meta">Published February 12, 2026 · 15 min read</p>
<p class="intro">TypeScript ships with over 20 built-in utility types that transform existing types into new ones. Instead of writing repetitive type definitions, utility types let you derive new types from your existing ones — making properties optional, picking subsets, creating dictionaries, extracting return types, and much more. This guide covers every built-in utility type with practical examples, then shows you how to build your own.</p>
<div class="tool-callout" style="background: rgba(59, 130, 246, 0.08); border: 1px solid rgba(59, 130, 246, 0.2); border-radius: 8px; padding: 1rem 1.25rem; margin: 1.5rem 0; line-height: 1.7; color: #d1d5db;">
<strong style="color: #3b82f6;">⚙ Try it:</strong> Use our <a href="/index.html?search=json-to-typescript" style="color: #3b82f6;">JSON to TypeScript Converter</a> to generate interfaces from JSON data, then apply utility types to transform them.
</div>
<nav class="toc">
<h2>Table of Contents</h2>
<ol>
<li><a href="#what-are-utility-types">What Are Utility Types?</a></li>
<li><a href="#object-utilities">Object Type Utilities</a></li>
<li><a href="#record-type">Record Type</a></li>
<li><a href="#union-utilities">Union Type Utilities</a></li>
<li><a href="#function-utilities">Function Type Utilities</a></li>
<li><a href="#string-utilities">String Utilities</a></li>
<li><a href="#promise-utilities">Promise Utilities</a></li>
<li><a href="#mapped-types">Mapped Types</a></li>
<li><a href="#conditional-types">Conditional Types</a></li>
<li><a href="#template-literal-types">Template Literal Types</a></li>
<li><a href="#custom-utility-types">Custom Utility Types</a></li>
<li><a href="#real-world-patterns">Real-World Patterns</a></li>
</ol>
</nav>
<!-- Section 1 -->
<section id="what-are-utility-types">
<h2>1. What Are Utility Types?</h2>
<p>Utility types are generic types built into TypeScript that take one or more type parameters and produce a transformed type. They solve a fundamental problem: you often need variations of an existing type without duplicating its definition.</p>
<pre><code class="language-typescript">interface User {
id: number;
name: string;
email: string;
password: string;
createdAt: Date;
}
// Without utility types: manual duplication
interface UserUpdate {
name?: string;
email?: string;
password?: string;
}
// With utility types: derive from the source type
type UserUpdate = Partial<Omit<User, "id" | "createdAt">>;
// { name?: string; email?: string; password?: string; }</code></pre>
<p>When the <code>User</code> interface changes, the derived type updates automatically. This is the core value of utility types: <strong>a single source of truth</strong> for your type definitions.</p>
</section>
<!-- Section 2 -->
<section id="object-utilities">
<h2>2. Object Type Utilities</h2>
<h3>Partial<T></h3>
<p>Makes all properties of <code>T</code> optional. Ideal for update operations where only some fields may be provided.</p>
<pre><code class="language-typescript">interface Config {
host: string;
port: number;
debug: boolean;
}
function updateConfig(current: Config, overrides: Partial<Config>): Config {
return { ...current, ...overrides };
}
// Only override what you need
updateConfig(defaultConfig, { debug: true });</code></pre>
<h3>Required<T></h3>
<p>The opposite of <code>Partial</code> — makes all properties required, removing any <code>?</code> modifiers.</p>
<pre><code class="language-typescript">interface FormFields {
name?: string;
email?: string;
age?: number;
}
// Ensure all fields are filled before submission
function submitForm(data: Required<FormFields>): void {
// data.name, data.email, data.age are all guaranteed to exist
console.log(`Submitting: ${data.name}, ${data.email}, ${data.age}`);
}</code></pre>
<h3>Readonly<T></h3>
<p>Makes all properties read-only. The compiler prevents reassignment after creation.</p>
<pre><code class="language-typescript">interface AppState {
user: string;
theme: "light" | "dark";
notifications: number;
}
function freeze(state: AppState): Readonly<AppState> {
return Object.freeze(state);
}
const state = freeze({ user: "Alice", theme: "dark", notifications: 3 });
// state.theme = "light"; // Error: Cannot assign to 'theme' (read-only)</code></pre>
<h3>Pick<T, K></h3>
<p>Creates a type with only the specified properties from <code>T</code>.</p>
<pre><code class="language-typescript">interface Product {
id: number;
name: string;
price: number;
description: string;
category: string;
stock: number;
}
// For a product card, we only need a subset
type ProductCard = Pick<Product, "id" | "name" | "price">;
// { id: number; name: string; price: number; }
function renderCard(product: ProductCard): string {
return `${product.name}: $${product.price}`;
}</code></pre>
<h3>Omit<T, K></h3>
<p>Creates a type with all properties from <code>T</code> except the specified keys. The complement of <code>Pick</code>.</p>
<pre><code class="language-typescript">// Remove sensitive fields before sending to the client
type PublicUser = Omit<User, "password">;
// { id: number; name: string; email: string; createdAt: Date; }
// Remove auto-generated fields for creation
type CreateProductInput = Omit<Product, "id">;
function createProduct(input: CreateProductInput): Product {
return { ...input, id: generateId() };
}</code></pre>
</section>
<!-- Section 3 -->
<section id="record-type">
<h2>3. Record Type</h2>
<p><code>Record<K, V></code> creates an object type with keys of type <code>K</code> and values of type <code>V</code>. It is the go-to type for dictionaries and lookup maps.</p>
<pre><code class="language-typescript">// String-keyed dictionary
type ErrorMessages = Record<string, string>;
const errors: ErrorMessages = {
name: "Name is required",
email: "Invalid email format"
};
// Union keys ensure every member is handled
type Status = "pending" | "active" | "archived";
type StatusConfig = Record<Status, { label: string; color: string }>;
const statusMap: StatusConfig = {
pending: { label: "Pending", color: "#f59e0b" },
active: { label: "Active", color: "#10b981" },
archived: { label: "Archived", color: "#6b7280" }
// Missing a status? TypeScript reports an error
};
// HTTP status code mapping
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
const handlers: Record<HttpMethod, (url: string) => void> = {
GET: (url) => fetch(url),
POST: (url) => fetch(url, { method: "POST" }),
PUT: (url) => fetch(url, { method: "PUT" }),
DELETE: (url) => fetch(url, { method: "DELETE" })
};</code></pre>
<p>When you use a union type for <code>K</code>, TypeScript enforces that every member of the union is present as a key, giving you exhaustive coverage.</p>
</section>
<!-- Section 4 -->
<section id="union-utilities">
<h2>4. Union Type Utilities</h2>
<h3>Exclude<T, U></h3>
<p>Removes members from a union type that are assignable to <code>U</code>.</p>
<pre><code class="language-typescript">type AllEvents = "click" | "scroll" | "mousemove" | "keydown" | "keyup";
// Remove mouse events
type KeyboardEvents = Exclude<AllEvents, "click" | "scroll" | "mousemove">;
// "keydown" | "keyup"
// Remove null and undefined
type Defined = Exclude<string | number | null | undefined, null | undefined>;
// string | number</code></pre>
<h3>Extract<T, U></h3>
<p>Keeps only members from <code>T</code> that are assignable to <code>U</code>. The opposite of <code>Exclude</code>.</p>
<pre><code class="language-typescript">type AllTypes = string | number | boolean | object | null;
type Primitives = Extract<AllTypes, string | number | boolean>;
// string | number | boolean
// Extract specific event types from a discriminated union
type AppEvent =
| { type: "user_login"; userId: string }
| { type: "user_logout"; userId: string }
| { type: "page_view"; url: string }
| { type: "error"; message: string };
type UserEvent = Extract<AppEvent, { type: "user_login" | "user_logout" }>;
// { type: "user_login"; userId: string } | { type: "user_logout"; userId: string }</code></pre>
<h3>NonNullable<T></h3>
<p>Removes <code>null</code> and <code>undefined</code> from <code>T</code>. A shorthand for <code>Exclude<T, null | undefined></code>.</p>
<pre><code class="language-typescript">type MaybeString = string | null | undefined;
type DefiniteString = NonNullable<MaybeString>; // string
// Useful with optional chaining results
function getEnvVar(key: string): string {
const value: string | undefined = process.env[key];
if (!value) throw new Error(`Missing env var: ${key}`);
return value; // narrowed to NonNullable<string | undefined> = string
}</code></pre>
</section>
<!-- Section 5 -->
<section id="function-utilities">
<h2>5. Function Type Utilities</h2>
<h3>ReturnType<T></h3>
<p>Extracts the return type of a function type. Invaluable when you need to type a variable based on what a function returns.</p>
<pre><code class="language-typescript">function createUser(name: string, role: "admin" | "user") {
return { id: crypto.randomUUID(), name, role, createdAt: new Date() };
}
// Derive the type from the function instead of duplicating it
type User = ReturnType<typeof createUser>;
// { id: string; name: string; role: "admin" | "user"; createdAt: Date; }
// Works with library functions you don't control
type FetchResult = ReturnType<typeof fetch>; // Promise<Response></code></pre>
<h3>Parameters<T></h3>
<p>Extracts parameter types as a tuple. Useful for wrapping or extending existing functions.</p>
<pre><code class="language-typescript">function log(level: "info" | "warn" | "error", message: string, meta?: object) {
console.log(`[${level}] ${message}`, meta);
}
type LogParams = Parameters<typeof log>;
// [level: "info" | "warn" | "error", message: string, meta?: object]
// Create a wrapper that adds a timestamp
function timedLog(...args: LogParams): void {
const [level, message, meta] = args;
log(level, `${new Date().toISOString()} ${message}`, meta);
}</code></pre>
<h3>ConstructorParameters<T></h3>
<p>Extracts constructor parameter types as a tuple, similar to <code>Parameters</code> but for class constructors.</p>
<pre><code class="language-typescript">class Database {
constructor(host: string, port: number, name: string) { /* ... */ }
}
type DbArgs = ConstructorParameters<typeof Database>;
// [host: string, port: number, name: string]
function createDatabase(...args: DbArgs): Database {
return new Database(...args);
}</code></pre>
</section>
<!-- Section 6 -->
<section id="string-utilities">
<h2>6. String Utilities</h2>
<p>TypeScript provides four intrinsic string manipulation types that work at the type level.</p>
<pre><code class="language-typescript">type Upper = Uppercase<"hello">; // "HELLO"
type Lower = Lowercase<"HELLO">; // "hello"
type Cap = Capitalize<"hello">; // "Hello"
type Uncap = Uncapitalize<"Hello">; // "hello"
// Practical: generate event handler names from event types
type EventName = "click" | "focus" | "blur";
type HandlerName = `on${Capitalize<EventName>}`;
// "onClick" | "onFocus" | "onBlur"
// Generate getter names from property names
type PropName = "name" | "age" | "email";
type GetterName = `get${Capitalize<PropName>}`;
// "getName" | "getAge" | "getEmail"</code></pre>
</section>
<!-- Section 7 -->
<section id="promise-utilities">
<h2>7. Promise Utilities</h2>
<p><code>Awaited<T></code> (TypeScript 4.5+) recursively unwraps <code>Promise</code> types to get the resolved value type.</p>
<pre><code class="language-typescript">type A = Awaited<Promise<string>>; // string
type B = Awaited<Promise<Promise<number>>>; // number
type C = Awaited<string | Promise<boolean>>; // string | boolean
// Most useful with async function return types
async function fetchUser(id: string) {
const res = await fetch(`/api/users/${id}`);
return res.json() as Promise<{ name: string; email: string }>;
}
// Get the resolved type, not Promise<...>
type UserData = Awaited<ReturnType<typeof fetchUser>>;
// { name: string; email: string }</code></pre>
</section>
<!-- Section 8 -->
<section id="mapped-types">
<h2>8. Mapped Types</h2>
<p>Mapped types iterate over keys of a type and transform each property. They are the foundation that built-in utility types like <code>Partial</code>, <code>Required</code>, and <code>Readonly</code> are built on.</p>
<pre><code class="language-typescript">// This is how Partial is implemented internally:
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
// And Readonly:
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
// Make all properties nullable
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
interface Settings {
theme: string;
fontSize: number;
language: string;
}
type NullableSettings = Nullable<Settings>;
// { theme: string | null; fontSize: number | null; language: string | null; }</code></pre>
<h3>Key Remapping with <code>as</code></h3>
<p>TypeScript 4.1 added key remapping, letting you transform property names during mapping.</p>
<pre><code class="language-typescript">// Add "get" prefix to all property names
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number; }
// Filter out properties by type (remove non-string properties)
type StringProps<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
type OnlyStrings = StringProps<{ name: string; age: number; email: string }>;
// { name: string; email: string; }</code></pre>
</section>
<!-- Section 9 -->
<section id="conditional-types">
<h2>9. Conditional Types</h2>
<p>Conditional types choose between two types based on a condition, using the <code>extends</code> keyword as a type-level <code>if</code> statement.</p>
<pre><code class="language-typescript">// Basic conditional type
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false
// Flatten arrays, leave other types unchanged
type Flatten<T> = T extends Array<infer Item> ? Item : T;
type Str = Flatten<string[]>; // string
type Num = Flatten<number>; // number</code></pre>
<h3>The <code>infer</code> Keyword</h3>
<p><code>infer</code> declares a type variable within a conditional type, letting you extract types from complex structures.</p>
<pre><code class="language-typescript">// Extract the element type from an array
type ElementOf<T> = T extends (infer E)[] ? E : never;
type Item = ElementOf<string[]>; // string
// Extract the resolved type from a Promise
type UnwrapPromise<T> = T extends Promise<infer R> ? R : T;
// Extract the return type of a function (how ReturnType works)
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
// Extract the first argument type
type FirstArg<T> = T extends (first: infer F, ...rest: any[]) => any ? F : never;
type First = FirstArg<(name: string, age: number) => void>; // string</code></pre>
<h3>Distributive Conditional Types</h3>
<p>When a conditional type acts on a union, it distributes across each member individually.</p>
<pre><code class="language-typescript">type ToArray<T> = T extends any ? T[] : never;
// Distributes over the union:
type Result = ToArray<string | number>;
// string[] | number[] (NOT (string | number)[])
// Prevent distribution by wrapping in a tuple:
type ToArrayNonDist<T> = [T] extends [any] ? T[] : never;
type Result2 = ToArrayNonDist<string | number>;
// (string | number)[]</code></pre>
</section>
<!-- Section 10 -->
<section id="template-literal-types">
<h2>10. Template Literal Types</h2>
<p>Template literal types use backtick syntax at the type level to construct string literal types from other types.</p>
<pre><code class="language-typescript">// Basic template literal type
type Greeting = `Hello, ${string}`;
const g: Greeting = "Hello, world"; // OK
// const g2: Greeting = "Hi, world"; // Error
// Combine with unions for powerful patterns
type Color = "red" | "blue" | "green";
type Shade = "light" | "dark";
type ColorVariant = `${Shade}-${Color}`;
// "light-red" | "light-blue" | "light-green" | "dark-red" | "dark-blue" | "dark-green"
// CSS property types
type CSSUnit = "px" | "rem" | "em" | "%";
type CSSValue = `${number}${CSSUnit}`;
const width: CSSValue = "100px"; // OK
const height: CSSValue = "2.5rem"; // OK
// Event listener pattern
type DOMEvent = "click" | "focus" | "blur" | "input";
type EventHandler = `on${Capitalize<DOMEvent>}`;
// "onClick" | "onFocus" | "onBlur" | "onInput"</code></pre>
<h3>Pattern Matching with Template Literals</h3>
<pre><code class="language-typescript">// Extract parts of a string type
type ExtractRoute<S extends string> =
S extends `/${infer Segment}/${infer Rest}`
? Segment | ExtractRoute<`/${Rest}`>
: S extends `/${infer Segment}`
? Segment
: never;
type Segments = ExtractRoute<"/users/123/posts">;
// "users" | "123" | "posts"</code></pre>
</section>
<!-- Section 11 -->
<section id="custom-utility-types">
<h2>11. Custom Utility Types</h2>
<p>Combining mapped types, conditional types, and <code>infer</code>, you can build powerful custom utility types for your projects.</p>
<h3>DeepPartial<T></h3>
<pre><code class="language-typescript">// Make ALL nested properties optional (Partial only affects top level)
type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
};
interface NestedConfig {
server: { host: string; port: number };
database: { connection: { host: string; port: number } };
}
type PartialConfig = DeepPartial<NestedConfig>;
// server?: { host?: string; port?: number; }
// database?: { connection?: { host?: string; port?: number; } }</code></pre>
<h3>DeepReadonly<T></h3>
<pre><code class="language-typescript">type DeepReadonly<T> = {
readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};</code></pre>
<h3>Mutable<T> (Remove readonly)</h3>
<pre><code class="language-typescript">type Mutable<T> = {
-readonly [K in keyof T]: T[K];
};
interface FrozenUser { readonly name: string; readonly email: string; }
type EditableUser = Mutable<FrozenUser>;
// { name: string; email: string; }</code></pre>
<h3>RequiredKeys<T> and OptionalKeys<T></h3>
<pre><code class="language-typescript">// Extract keys that are required vs optional
type RequiredKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
}[keyof T];
type OptionalKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? K : never;
}[keyof T];
interface Mixed { name: string; age: number; nickname?: string; bio?: string; }
type Req = RequiredKeys<Mixed>; // "name" | "age"
type Opt = OptionalKeys<Mixed>; // "nickname" | "bio"</code></pre>
<h3>PickByType<T, V></h3>
<pre><code class="language-typescript">// Pick only properties whose values match a given type
type PickByType<T, V> = {
[K in keyof T as T[K] extends V ? K : never]: T[K];
};
interface Mixed { name: string; age: number; active: boolean; email: string; }
type StringFields = PickByType<Mixed, string>;
// { name: string; email: string; }</code></pre>
</section>
<!-- Section 12 -->
<section id="real-world-patterns">
<h2>12. Real-World Patterns</h2>
<h3>API Response Types</h3>
<pre><code class="language-typescript">// Generic API response wrapper
type ApiResponse<T> = {
data: T;
status: number;
message: string;
timestamp: string;
};
type ApiError = {
error: string;
code: number;
details?: Record<string, string[]>;
};
type ApiResult<T> = ApiResponse<T> | ApiError;
// Derive request types from your models
interface Article {
id: string;
title: string;
body: string;
author: string;
publishedAt: Date;
updatedAt: Date;
}
type CreateArticle = Omit<Article, "id" | "publishedAt" | "updatedAt">;
type UpdateArticle = Partial<Pick<Article, "title" | "body">>;
type ArticlePreview = Pick<Article, "id" | "title" | "author" | "publishedAt">;</code></pre>
<h3>Form Handling</h3>
<pre><code class="language-typescript">// Type-safe form state
type FormState<T> = {
values: T;
errors: Partial<Record<keyof T, string>>;
touched: Partial<Record<keyof T, boolean>>;
isSubmitting: boolean;
};
interface LoginForm { email: string; password: string; remember: boolean; }
type LoginFormState = FormState<LoginForm>;
// {
// values: { email: string; password: string; remember: boolean; };
// errors: { email?: string; password?: string; remember?: string; };
// touched: { email?: boolean; password?: boolean; remember?: boolean; };
// isSubmitting: boolean;
// }
// Type-safe field change handler
type FieldHandler<T> = <K extends keyof T>(field: K, value: T[K]) => void;
const handleChange: FieldHandler<LoginForm> = (field, value) => {
// field is narrowed to "email" | "password" | "remember"
// value matches the field's type
};</code></pre>
<h3>State Management</h3>
<pre><code class="language-typescript">// Type-safe action creators from a state shape
type ActionMap<T> = {
[K in keyof T]: T[K] extends undefined
? { type: K }
: { type: K; payload: T[K] };
};
interface PayloadTypes {
SET_USER: { name: string; id: string };
SET_THEME: "light" | "dark";
LOGOUT: undefined;
}
type Actions = ActionMap<PayloadTypes>[keyof PayloadTypes];
// { type: "SET_USER"; payload: { name: string; id: string } }
// | { type: "SET_THEME"; payload: "light" | "dark" }
// | { type: "LOGOUT" }
function reducer(state: AppState, action: Actions): AppState {
switch (action.type) {
case "SET_USER":
return { ...state, user: action.payload }; // payload is typed
case "SET_THEME":
return { ...state, theme: action.payload }; // "light" | "dark"
case "LOGOUT":
return { ...state, user: null };
}
}</code></pre>
<h3>Builder Pattern with Chained Generics</h3>
<pre><code class="language-typescript">// Type-safe query builder
type QueryResult<
Selected extends string,
Table extends string
> = Record<Selected, unknown> & { __table: Table };
class QueryBuilder<T extends string = never, Table extends string = string> {
select<K extends string>(...cols: K[]): QueryBuilder<T | K, Table> {
return this as any;
}
from<TName extends string>(table: TName): QueryBuilder<T, TName> {
return this as any;
}
execute(): QueryResult<T, Table>[] {
return [] as any;
}
}
const results = new QueryBuilder()
.select("name", "email")
.from("users")
.execute();
// QueryResult<"name" | "email", "users">[]</code></pre>
</section>
<!-- FAQ Section -->
<section id="faq" class="faq-section">
<h2>Frequently Asked Questions</h2>
<details>
<summary>What are TypeScript utility types?</summary>
<div class="faq-answer">
<p>TypeScript utility types are built-in generic types that transform existing types into new ones. They let you make properties optional (<code>Partial</code>), required (<code>Required</code>), read-only (<code>Readonly</code>), pick specific properties (<code>Pick</code>), omit properties (<code>Omit</code>), create dictionaries (<code>Record</code>), and extract or exclude union members (<code>Extract</code>, <code>Exclude</code>). They eliminate repetitive type definitions and keep your codebase DRY.</p>
</div>
</details>
<details>
<summary>What is the difference between Pick and Omit in TypeScript?</summary>
<div class="faq-answer">
<p><code>Pick<T, K></code> creates a new type by selecting specific properties <code>K</code> from type <code>T</code>, while <code>Omit<T, K></code> creates a new type by removing properties <code>K</code> from type <code>T</code>. They are complementary: Pick is better when you want a small subset of properties, and Omit is better when you want most properties but need to exclude a few. For example, <code>Pick<User, "name" | "email"></code> keeps only name and email, while <code>Omit<User, "password"></code> keeps everything except password.</p>
</div>
</details>
<details>
<summary>How do I create custom utility types in TypeScript?</summary>
<div class="faq-answer">
<p>Custom utility types are built using mapped types, conditional types, and the <code>infer</code> keyword. A mapped type iterates over keys of a type using the <code>[K in keyof T]</code> syntax and transforms each property. Conditional types use the <code>T extends U ? X : Y</code> pattern to branch based on type relationships. The <code>infer</code> keyword extracts types from within other types. For example, <code>type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] }</code> makes all nested properties optional.</p>
</div>
</details>
<details>
<summary>When should I use Record vs a regular interface in TypeScript?</summary>
<div class="faq-answer">
<p>Use <code>Record<K, V></code> when you need a dictionary or map-like structure where all values share the same type, especially with dynamic or union keys. Use an interface when each property has a different type or when you need declaration merging. For example, <code>Record<string, number></code> is ideal for a scores dictionary, while an interface is better for a User object with name (string), age (number), and active (boolean) properties.</p>
</div>
</details>
<details>
<summary>What is the Awaited utility type in TypeScript?</summary>
<div class="faq-answer">
<p><code>Awaited<T></code> (TypeScript 4.5+) recursively unwraps Promise types to get the resolved value type. <code>Awaited<Promise<string>></code> gives you <code>string</code>, and <code>Awaited<Promise<Promise<number>>></code> gives you <code>number</code>. It is especially useful with <code>ReturnType</code> when working with async functions: <code>type Result = Awaited<ReturnType<typeof fetchUser>></code> gives you the resolved return type of an async function rather than a Promise.</p>
</div>
</details>
</section>
<h2>Related Resources</h2>
<ul>
<li><a href="/index.html?search=typescript-tips-and-tricks">TypeScript Tips and Tricks</a> — 15 practical patterns for cleaner TypeScript code</li>
<li><a href="/index.html?search=typescript-complete-guide">TypeScript Complete Guide</a> — comprehensive guide from basics to advanced TypeScript</li>
<li><a href="/index.html?search=typescript-types">TypeScript Types Cheat Sheet</a> — quick reference for all built-in types</li>
<li><a href="/index.html?search=json-to-typescript">JSON to TypeScript Converter</a> — generate TypeScript interfaces from JSON data</li>
<li><a href="/json-formatter.html">JSON Formatter</a> — format and validate JSON for your TypeScript projects</li>
</ul>
<p style="margin-top:2rem;padding:1.5rem;background:var(--surface);border:1px solid var(--border);border-radius:8px;">
<strong>Keep learning:</strong> Utility types are one piece of the TypeScript puzzle. Our <a href="/index.html?search=typescript-tips-and-tricks">TypeScript Tips and Tricks</a> guide covers const assertions, discriminated unions, branded types, and more patterns that pair perfectly with utility types. Use the <a href="/index.html?search=typescript-types">TypeScript Types Cheat Sheet</a> for a quick reference while coding.
</p>
</article>
</main>
<section style="max-width: 800px; margin: 2.5rem auto; padding: 0 1rem;">
<h2 style="margin-bottom: 1rem; font-size: 1.4rem;">Related Resources</h2>
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 1rem;">
<a href="/index.html?search=typescript-tips-and-tricks" style="display: block; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 1rem 1.25rem; text-decoration: none; transition: border-color 0.2s, background 0.2s;">
<div style="font-weight: 600; color: #e4e4e7; margin-bottom: 0.25rem;">TypeScript Tips and Tricks</div>
<div style="color: #9ca3af; font-size: 0.9rem;">15 practical patterns for cleaner TypeScript</div>
</a>
<a href="/index.html?search=typescript-types" style="display: block; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 1rem 1.25rem; text-decoration: none; transition: border-color 0.2s, background 0.2s;">
<div style="font-weight: 600; color: #e4e4e7; margin-bottom: 0.25rem;">TypeScript Types Cheat Sheet</div>
<div style="color: #9ca3af; font-size: 0.9rem;">Quick reference for all built-in types</div>
</a>
<a href="/index.html?search=json-to-typescript" style="display: block; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 1rem 1.25rem; text-decoration: none; transition: border-color 0.2s, background 0.2s;">
<div style="font-weight: 600; color: #e4e4e7; margin-bottom: 0.25rem;">JSON to TypeScript Converter</div>
<div style="color: #9ca3af; font-size: 0.9rem;">Generate interfaces from JSON data</div>
</a>
<a href="/json-formatter.html" style="display: block; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 1rem 1.25rem; text-decoration: none; transition: border-color 0.2s, background 0.2s;">
<div style="font-weight: 600; color: #e4e4e7; margin-bottom: 0.25rem;">JSON Formatter</div>
<div style="color: #9ca3af; font-size: 0.9rem;">Format and validate JSON for TypeScript APIs</div>
</a>
</div>
</section>
<footer><p>DevToolbox — Free developer tools, no strings attached.</p></footer>
<script src="/js/track.js" defer></script>
<script>
document.addEventListener('keydown', function(e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
e.preventDefault();
window.location.href = '/tools/';
}
});
</script>
<style>
.faq-section { margin-top: 3rem; }
.faq-section details { background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 6px; margin-bottom: 1rem; padding: 0; }
.faq-section summary { color: #3b82f6; font-weight: bold; cursor: pointer; padding: 1rem 1.5rem; font-size: 1.1rem; }
.faq-section summary:hover { color: #60a5fa; }
.faq-answer { padding: 0 1.5rem 1rem; color: #d1d5db; line-height: 1.7; }
.faq-answer p { margin: 0; }
</style>
</body>
</html>