Reusable generic types in TypeScript

JS
R
JavaScript

Use types for flexibility and complex type operations. Use interfaces for simple object shapes and when extending/implementing.

1// Example 1
2type StringWithAutocompleteOptions<T extends string> = T | (string & {});
3type Color = StringWithAutocompleteOptions<"red" | "blue">;
4// Color will suggest "red" and "blue", but allow any string
5
6// Example 2
7type HttpMethod<T extends string> = T | (string & {});
8type ValidMethod = HttpMethod<"GET" | "POST" | "PUT" | "DELETE">;
9function makeRequest(url: string, method: ValidMethod) {
10  // Implementation
11}
12makeRequest("https://api.example.com", "GET"); // Autocompletes
13makeRequest("https://api.example.com", "PATCH"); // Also valid, no error

Created on 10/22/2024