Bài tập: Khớp route và lấy tham số /users/:id
Ở bài Template literal type, bạn đã thấy kiểu Params<Path> trích tên tham số từ route. Giờ hãy viết phần runtime: hàm khớp một đường dẫn với mẫu route và trả về các tham số.
function matchRoute<P extends string>(pattern: P, path: string): Record<Params<P>, string> | nullQuy tắc:
- Tách
patternvàpaththeo/, bỏ các đoạn rỗng (nên/users/5/khớp/users/:idvà ngược lại;/là route không có đoạn nào). - Bỏ phần query string của
path(từ dấu?trở đi) trước khi so khớp. - Số đoạn phải bằng nhau. Đoạn bắt đầu bằng
:là tham số, khớp với bất kỳ đoạn nào và lưu giá trị đã giải mã bằngdecodeURIComponent. Đoạn tĩnh phải bằng nhau chính xác (phân biệt hoa thường). - Khớp → trả về object tham số (route không có tham số trả về
{}); không khớp →null.
Ví dụ
const m = matchRoute("/users/:userId/posts/:postId", "/users/7/posts/99");
// kiểu: Record<"userId" | "postId", string> | null
// giá trị: { userId: "7", postId: "99" }
m?.userId; // ✅
m?.id; // ❌ lỗi kiểu
matchRoute("/products/:slug", "/products/ao-thun?color=red"); // { slug: "ao-thun" }
matchRoute("/search/:q", "/search/%C3%A1o%20thun"); // { q: "áo thun" }
matchRoute("/about", "/about/team"); // nullKiểu Params<P> đã có sẵn trong starter code, bạn chỉ cần viết thân hàm.
NOTE
Giải mã sau khi tách đoạn: /files/a%2Fb cho { name: "a/b" }, không phải hai đoạn a và b.
Trình chấm in
JSON.stringifycủa kết quả cho từng cặppattern path.
Examples
Example 1
Input
/users/:id /users/42 /users/:id /posts/42 /users/:userId/posts/:postId /users/7/posts/99
Expected output
{"id":"42"}
null
{"userId":"7","postId":"99"}Example 2
Input
/about /about /about /about/team /products/:slug /products/ao-thun?color=red
Expected output
{}
null
{"slug":"ao-thun"}6 hidden tests · Limit 2 s · 256 MB
type Params<P extends string> = P extends `${string}:${infer Name}/${infer Rest}`
? Name | Params<`/${Rest}`>
: P extends `${string}:${infer Name}`
? Name
: never;
function matchRoute<P extends string>(pattern: P, path: string): Record<Params<P>, string> | null {
// trả về object tham số, hoặc null nếu không khớp
}
Comments