YouTip LogoYouTip

Ts Literal Types

\\ Literal Types is a feature in TypeScript that represents specific values rather than generic types.\\ \\ It allows us to restrict variable types to specific values rather than broad types like string and number.\\ \\ This provides more precise type control, making code more type-safe.\\ \\ * * *\\ \\ * * *\\ \\ ## Why Literal Types are Needed\\ \\ In TypeScript, default types like string and number are too broad.\\ \\ Sometimes we need more precise type control. For example, a variable can only take specific values.\\ \\ Literal types are designed to solve such problems.\\ \\ > **Concept Explanation:** Literal types are specific values of generic types (string, number). For example, "up" is a subtype of string, and the only values that can be assigned to it are specific strings.\\ \\ * * *\\ \\ ## String Literal Types\\ \\ String literal types restrict variable values to specific strings.\\ \\ This is very useful when you need to restrict a variable to only certain fixed values.\\ \\ ## Example\\ \\ // Define string literal type\\ \\ // direction can only be one of four specific values\\ \\ var direction:"up"|"down"|"left"|"right";\\ \\ // Correct: assign a value from the literal type\\ \\ direction ="up";\\ \\ // Incorrect: assign a value not in the list\\ \\ // direction = "upup"; // Compilation error!\\ \\ console.log("Direction: "+ direction);\\ \\ // Use type alias to create reusable literal type\\ \\ // Define status type: can only be one of three fixed values\\ \\ type Status ="pending"|"active"|"completed";\\ \\ // Use type alias\\ \\ var currentStatus: Status ="active";\\ \\ console.log("State: "+ currentStatus);\\ \\ **Output:**\\ \\ Direction: up State: active\\ > **Application Scenarios:** String literals are commonly used for defining enum values, status codes, configuration options, and other scenarios where you need to restrict to specific values.\\ \\ * * *\\ \\ ## Number Literal Types\\ \\ Number literal types restrict variable values to specific numbers.\\ \\ This is very useful when you need to use specific numeric values (such as status codes, error codes).\\ \\ ## Example\\ \\ // Define number literal type\\ \\ // code can only be one of three specific values\\ \\ var code:200|404|500;\\ \\ // Correct: assign 200\\ \\ code =200;\\ \\ // Incorrect: assign a value not in the list\\ \\ // code = 301; // Compilation error!\\ \\ console.log("Statecode: "+ code);\\ \\ // Use number literal to simulate enum\\ \\ // Define days of the week\\ \\ type Weekday =1|2|3|4|5|6|7;\\ \\ // Can only assign numbers between 1-7\\ \\ var today: Weekday =1;\\ \\ console.log("Day of Week: "+ today);\\ \\ > **Explanation:** Number literals can replace simple enums (enum), especially when you only need a few fixed numeric values.\\ \\ * * *\\ \\ ## Boolean Literal Types\\ \\ Boolean literal types restrict variable values to true or false.\\ \\ In fact, the boolean type in TypeScript is an alias for true | false.\\ \\ ## Example\\ \\ // Define boolean literal type\\ \\ // isActive can only be true or false\\ \\ var isActive:true|false;\\ \\ // Assign true\\ \\ isActive =true;\\ \\ // Actually boolean is a union type of true | false\\ \\ // So these twoSyntax are equivalent\\ \\ var flag:boolean=true;\\ \\ console.log("Activation Status: "+ isActive);\\ \\ > **Tip:** Although boolean is sufficient for most use cases, when you need to explicitly distinguish between true and false types, you can use true or false as types.\\ \\ * * *\\ \\ ## Object Literal Types\\ \\ Object literal types can define the structure of objects, and you can use the readonly modifier to make properties read-only.\\ \\ This is very useful when you need to create immutable objects.\\ \\ ## Example\\ \\ // Define object literal type\\ \\ // Specify object structure and property types\\ \\ type Point ={\\ \\ // x coordinate of the point\\ \\ x: number;\\ \\ // y coordinate of the point\\ \\ y: number;\\ \\ };\\ \\ // Use object literal type\\ \\ var p: Point ={ x:10, y:20};\\ \\ console.log("Dot: "+ JSON.stringify(p));\\ \\ // Define readonly object type\\ \\ // Use readonly modifier to make properties read-only\\ \\ type ReadonlyPoint ={\\ \\ // readonly x coordinate\\ \\ readonly x: number;\\ \\ // readonly y coordinate\\ \\ readonly y: number;\\ \\ };\\ \\ // Use readonly object type\\ \\ var rp: ReadonlyPoint ={ x:1, y:2};\\ \\ // Attempting to modify readonly property will cause error\\ \\ // rp.x = 3; // Compilation error: readonly properties cannot be modified\\ \\ console.log("Read-only Dot: "+ JSON.stringify(rp));\\ \\ **Output:**\\ \\ Dot: {"x":10,"y":20}Read-only Dot: {"x":1,"y":2}\\ > **Application Scenarios:** Readonly objects are commonly used for defining configuration objects, constant objects, and other data that should not be modified.\\ \\ * * *\\ \\ ## Literal Types and Type Inference\\ \\ TypeScript automatically infers literal types based on how variables are declared.\\ \\ Variables declared with const are inferred as specific literal types rather than broad types.\\ \\ ## Example\\ \\ // Declare and assign using var\\ \\ // TypeScript infers as broad type\\ \\ var name ="Alice";// Type: string (because var can be reassigned)\\ \\ var age =25;// Type: number\\ \\ var enabled =true;// Type: boolean\\ \\ console.log("Name: "+ name +", Age: "+ age +", Enable: "+ enabled);\\ \\ // Use as const to create deeply readonly literal\\ \\ // Array becomes readonly tuple, values are literal types\\ \\ var colors =["red","green","blue"] as const;\\ \\ // colors type becomes:\\ \\ // readonly ["red", "green", "blue"]\\ \\ // Access array elements\\ \\ console.log("color: "+ colors);\\ \\ // Attempting to modify will cause error\\ \\ // colors = "yellow"; // Compilation error: readonly\\ \\ > **Explanation:** `as const` infers the type as the most specific literal type and adds the readonly modifier.\\ \\ * * *\\ \\ ## Template Literal Types\\ \\ Template literal types use JavaScript template string syntax to create new types.\\ \\ They allow us to dynamically generate string types.\\ \\ ## Example\\ \\ // Use template literal type to define event names\\ \\ // `on${string}` represents any string starting with "on"\\ \\ type EventName = `on${string}`;\\ \\ // Use template literal type to define handler names\\ \\ // Capitalize capitalizes the first letter of the string\\ \\ type Handler = `handle${Capitalize}`;\\ \\ // Use template literal type\\ \\ var event: EventName ="onClick";\\ \\ var handler: Handler ="handleSubmit";\\ \\ console.log("Event: "+ event);\\ \\ console.log("Handler: "+ handler);\\ \\ // Error: doesn't match template format\\ \\ // var e: EventName = "click"; // Compilation error: doesn't start with "on"\\ \\ **Output:**\\ \\ Event: onClick Handler: handleSubmit\\ > **Built-in Utility Types:** Template literal types can be used with built-in utility types like Uppercase, Lowercase, Capitalize, Uncapitalize, etc.\\ \\ * * *\\ \\ ## Practical Application: Redux Action\\ \\ Literal types have wide applications in actual development.\\ \\ Below shows how to implement Redux-style actions using literal types.\\ \\ ## Example\\ \\ // Define Redux-style Action type\\ \\ // Use union type to define different types of Actions\\ \\ type Action =\\ \\ // Increment type Action, contains number payload\\ \\ |{ type:"increment"; payload: number }\\ \\ // Decrement type Action, contains number payload\\ \\ |{
← Ts Access ModifiersTs Promise β†’