Senior #template-literal-types#string-types#advanced-types
Template literal types là gì? Ứng dụng thực tế
⚡ Trả lời nhanh
Template literal type dựng string type từ các literal khác bằng cú pháp template, ví dụ `on${Capitalize<E>}`. Khi gặp union, nó sinh tích Descartes của mọi tổ hợp. Kết hợp `infer` để parse chuỗi (route params, event name) và với key remapping của mapped type để sinh API.
Cú pháp và ví dụ
type Event = "click" | "focus";
type Handler = `on${Capitalize<Event>}`; // "onClick" | "onFocus"
type Axis = "x" | "y";
type Side = "top" | "bottom";
type Pos = `${Axis}-${Side}`; // 4 tổ hợp
// parse route params bằng infer
type Params<S extends string> =
S extends `${string}:${infer P}/${infer Rest}` ? P | Params<`/${Rest}`>
: S extends `${string}:${infer P}` ? P
: never;
type R = Params<"/users/:id/posts/:postId">; // "id" | "postId"
// sinh getter từ object type
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
- Có các helper chuỗi dựng sẵn:
Uppercase,Lowercase,Capitalize,Uncapitalize. infertrong template literal khớp chuỗi theo mẫu, và quy tắc là khớp ngắn nhất cho mỗiinferđứng trước một literal.- Ứng dụng: typed event emitter, key path (
"user.address.city"), kiểu cho thư viện route, CSS-in-JS, i18n key.