Dark mode
Template Literal Types
ช่วยให้เราสามารถสร้างประเภทจาก template strings ได้
Basic Syntax
String Composition
สร้าง string literal type จาก template string
ts
type World = "world";
type Greeting = `hello ${World}`; // "hello world"
Union Types
เมื่อใช้กับ union type จะสร้างผลลัพธ์เป็นทุก combination ที่เป็นไปได้
ts
type EmailLocaleIDs = "welcome_email" | "email_heading";
type FooterLocaleIDs = "footer_title" | "footer_sendoff";
type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;
Practical Applications
Dynamic Routes
ใช้สร้าง type สำหรับ path ที่มีรูปแบบแน่นอน
ts
type Route = `/${string}`;
function navigate(route: Route) {
// ...
}
CSS-in-JS
เหมาะสำหรับการสร้าง type ของ class name ที่มีรูปแบบเฉพาะ
ts
type Size = "small" | "medium" | "large";
type Color = "primary" | "secondary";
type ButtonStyle = `btn-${Size}-${Color}`;
Internationalization
ใช้สร้าง type สำหรับ key ในการแปลภาษา
- ตัวอย่างจริง
ts
// ตัวอย่างโค้ดสำหรับ Internationalization