Middle
Implement TypeScript typing for URL validation to allow only correct URLs of the form: base domain + path (users/orders/messages) + method (get/update/delete/ban). Arbitrary strings should cause a compile error.
sobes.tech AI
Answer from AI
To type URLs with a base domain, path (users/orders/messages), and method (get/update/delete/ban), you can use literal types and template strings in TypeScript.
// Define valid parts of the URL
type BaseDomain = "example.com";
type Path = "users" | "orders" | "messages";
type Method = "get" | "update" | "delete" | "ban";
// Form the URL type as a template string
type ValidURL = `${BaseDomain}/${Path}/${Method}`;
// Usage example
const url1: ValidURL = "example.com/users/get"; // OK
const url2: ValidURL = "example.com/orders/ban"; // OK
const url3: ValidURL = "example.com/products/get"; // Compilation error
const url4: ValidURL = "example.com/users/create"; // Compilation error
This approach allows compile-time checking that strings strictly match the specified URL format.