Code Logo

Literal Union Type

Published at25 Jul 2026
TypeScript Generics & Advanced Types Easy 0 views
Like0

Write a TypeScript function that takes a size parameter of literal union type "small" | "medium" | "large" and returns a corresponding numeric value. Literal union types restrict a parameter to only the specified exact values, providing compile-time safety against invalid inputs.

Literal types in TypeScript allow you to specify exact values as types. A string literal type like "small" means that parameter can only be the exact string "small". Union types combine multiple literal types with the | operator: "small" | "medium" | "large". The TypeScript compiler will report an error if you pass any value outside this union.

Literal union types are a powerful TypeScript feature with no equivalent in JavaScript. They enable pattern matching-like behavior, discriminated unions, and compile-time validation of string constants. They are commonly used for configuration options, action types in Redux, and API parameter validation.

Time complexity is O(1) as the function performs a simple lookup or comparison. Space complexity is O(1). The literal union type is enforced at compile time and erased at runtime with no overhead.

Edge cases include passing values outside the union (caught by the compiler), case sensitivity (the type is exact), and combining literal types with other types in a union.

Example Input & Output

Example 1
Input
"large"
Output
30
Explanation

Large maps to 30

Example 2
Input
"medium"
Output
20
Explanation

Medium maps to 20

Example 3
Input
"small"
Output
10
Explanation

Small check

Example 4
Input
"small"
Output
10
Explanation

Small size maps to 10

Example 5
Input
"large"
Output
30
Explanation

Large check

Algorithm Flow

Recommendation Algorithm Flow for Literal Union Type
Recommendation Algorithm Flow for Literal Union Type

Solution Approach

type Size = 'small' | 'medium' | 'large';

function solution(s: Size): number {
  if (s === 'small') return 10;
  if (s === 'medium') return 20;
  return 30;
}

Best Answers

typescript - Approach 1
type Size = 'small' | 'medium' | 'large';

function solution(s: Size): number {
  if (s === 'small') return 10;
  if (s === 'medium') return 20;
  return 30;
}