Template Literal Types की जानकारी
In this page:
type Name = `${string}-${string}`;
type Union = `${"a" | "b"}_${"x" | "y"}`;
Basic Template Literal Type
एक template literal type backticks और placeholders उपयोग करता है, बिल्कुल एक JavaScript template string जैसा, existing string literal types को नए, ज़्यादा specific string literal types में combine करने के लिए।
उदाहरण: Basic Template Literal Type
type Greeting = `Hello, ${string}!`;
const g: Greeting = "Hello, Ravi!";
console.log(g);
Combining Unions
Template literal types कई unions combine कर सकते हैं उनके members का हर valid combination produce करने के लिए, जो छोटे pieces से related string values का एक exhaustive set generate करने के लिए उपयोगी है।
उदाहरण: Combining Unions
type Direction = "top" | "bottom";
type Side = "left" | "right";
type Combo = `${Direction}-${Side}`;
const c: Combo = "bottom-right";
console.log(c);
Event Names
Template literal types property names से predictable, structured event names बना सकते हैं — उदाहरण के लिए एक property click को अपने आप एक event type onClick में बदलना।
उदाहरण: Event Names
type Prop = "click" | "hover";
type EventName = `on${Capitalize<Prop>}`;
const e: EventName = "onClick";
console.log(e);
Intrinsic String Utilities
Template literal types built-in string utility types जैसे Uppercase, Lowercase, और Capitalize के साथ मिलकर काम करते हैं वे जो string literal types produce करते हैं उनकी casing transform करने के लिए।
उदाहरण: Intrinsic String Utilities
type Loud = Uppercase<"hello">;
type Quiet = Lowercase<"WORLD">;
const loud: Loud = "HELLO";
const quiet: Quiet = "world";
console.log(loud, quiet);
Practical Template Literal Types
Template literal types APIs, event systems, CSS-like values, और किसी भी और जगह के लिए उपयोगी हैं जहां string values एक predictable, structured pattern follow करती हैं जो type level पर enforce करने लायक है।
उदाहरण: Practical Template Literal Types
type HttpMethod = "GET" | "POST";
type Endpoint = "users" | "orders";
type Route = `${HttpMethod} /${Endpoint}`;
const r: Route = "POST /users";
console.log(r);
- Backticks के बजाय single या double quotes उपयोग करना, जैसे
"Hello, ${string}", जो सिर्फ एक string literal type है। - बड़े unions combine करना और huge results से surprised होना, क्योंकि members की संख्या multiply होती है।
- एक value assign करना जो pattern से match नहीं करता, जैसे
"Hi, Ravi!"कोHello, ${string}!में।
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- TypeScript Advanced Types
- Mapped Types
- Conditional Types
- Custom Type Guards
- Assertion Functions
- Control Flow Analysis
- Exhaustiveness Checking
- Satisfies Operator
- Template Literal Types
- Utility Types - Partial
- Utility Types - Required
- Utility Types - Readonly
- Utility Types - Pick
- Utility Types - Omit
- Utility Types - Record
- Utility Types - Exclude and Extract
- Utility Types - NonNullable
- Utility Types - ReturnType
- Utility Types - Parameters
- TypeScript 5 Updates