Literal के Types
In this page:
let variable: "value1" | "value2" | "value3";
type Literal = 1 | 2 | 3;
String Literal Types
एक string literal type एक single, exact string value represent करता है, जैसे general type string के बजाय type admin। कई string literals को एक union के साथ combine करना, जैसे admin | editor | viewer, allowed choices का एक controlled, closed set बनाता है।
उदाहरण: String Literal Types
type Role = 'admin' | 'editor';
let role: Role = 'admin';
console.log(role);
Number Literal Types
Number literal types numbers के लिए उसी तरह काम करते हैं, एक value को किसी भी number के बजाय एक या ज़्यादा specific exact numbers तक restrict करते हैं।
वे खासकर तब handy हैं जब वाकई सिर्फ एक छोटा, fixed set ही valid options हो, जैसे HTTP status codes।
उदाहरण: Number Literal Types
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
let roll: DiceRoll = 4;
console.log(roll);
Boolean Literal Types
Boolean literal types एक value को exactly true या exactly false तक अपने distinct type के रूप में restrict कर सकते हैं, general boolean type के बजाय जो दोनों allow करता है।
यह day-to-day कम common है पर एक specific, fixed object state model करते समय उपयोगी हो सकता है।
उदाहरण: Boolean Literal Types
type AlwaysTrue = true;
let flag: AlwaysTrue = true;
console.log(flag);
Literal Types in Functions
Function parameters में literal types callers को एक specific, supported set से बाहर कोई भी value pass करने से रोकते हैं, typos और unsupported options को runtime के बजाय compile time पर पकड़ते हुए।
वे editors को valid values के लिए precise autocomplete suggestions देने के लिए भी enough information देते हैं।
उदाहरण: Literal Types in Functions
function setAlign(value: 'left' | 'center' | 'right') {
console.log(`Aligned: ${value}`);
}
setAlign('center');
Literal Types with Type Aliases
एक literal union को एक type alias के साथ pair करना, जैसे type Theme = light | dark, उस allowed values के set को codebase में variables, functions, और object properties में reusable बनाता है।
यह application states और fixed configuration options represent करने के लिए एक common और effective pattern है।
उदाहरण: Literal Types with Type Aliases
type Theme = 'light' | 'dark';
let theme: Theme = 'dark';
console.log(theme);
let role = adminकोletके साथ declare करना और literal type की उम्मीद करना, जब यहstringतक widen हो जाता है।- Union के बाहर एक value assign करना, जैसे
guestकोadmin | editorमें। DiceRollजैसे एक literal के लिए गलत number उपयोग करना, जैसे7, जो reject हो जाता है।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: