Type System

TS Literal Types

Using Literal Types

TypeScript literal types restrict values to specific literals like "success".

Introduction to Literal Types

TypeScript's literal types allow you to specify exact values a variable can hold. This feature enhances type safety by ensuring variables are only assigned predefined values. Literal types can be strings, numbers, or booleans.

String Literal Types

String literal types restrict a variable to a set of string values. This is useful when a function or a component should only accept specific string inputs.

Numeric Literal Types

Numeric literal types allow you to constrain a variable to specific numbers. This can be useful for values that are restricted to a known set of numbers, such as status codes.

Boolean Literal Types

Boolean literal types are less common but can be used to specify explicit true or false values for a variable. This ensures that a variable only receives a specific boolean value.

Using Literal Types in Functions

Literal types can be very powerful when used with functions. By specifying literal types as parameters, you can enforce stricter input types, which reduces bugs and improves code readability.

Combining Literal Types with Unions

Literal types can be combined with union types to create more complex and expressive type definitions. This combination is particularly powerful when modeling states or options that a variable can have.