Write branded UserId and ProductId types, so one can't be passed where the other is expected.
Both ids are strings at runtime, so TypeScript treats the two aliases below as the same type, and getUser(productId) compiles. Make them distinct types that are still strings, with toUserId and toProductId as the only way to create them. A user id starts with u_ and a product id with p_; throw an error for anything else.
type UserId = string;type ProductId = string; function toUserId(id: string): UserId { return id;} function toProductId(id: string): ProductId { return id;} // declare function getUser(id: UserId): void;// getUser(toUserId("u_1")); // OK// getUser(toProductId("p_1")); // should be a type error// getUser("u_1"); // should be a type errorThe answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…