Posts > TS Basic: Literal Types

TS Basic: Literal Types

  • Literal types allow you to define exact values that a variable or property can take on.
  • by themselves, literal types aren’t very valuable
  • by combining literals into a union, you can express a more useful concept
function printText(s: string, alignment: 'left' | 'right' | 'center'){
	//rest of code
}

printText('Hello', 'right')
👌This feature provides more PRECISE TYPE CHECKING and helps enforce STRICTER constraints on the values that can be assigned.

String Literal Types

let userStatus : 'sucess' | 'error'
userStatus = 'success' // ok
userStatus = 'failure' // error: Type '"failure"' is not assignable to type '"success" | "error"'.

Numeric Literal Types

let diceRoll: 1 | 2 | 3 | 4 | 5 | 6;
diceRoll = 5; // ok
diceRoll = 8; // error: Type '8' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6'.

Boolean Literal Types

  • literal types can also be used in combination with union types to create more complex constraints.
type Size = 'small' | 'medium' | 'large';
type Color = 'red' | 'green' | 'blue';

function createBox(size: Size, color: Color){
	//rest of code
}

createBox('small','red'); //valid
createBox('extra-small', 'yellow'); // invalid

Enum Literal Types

enum Direction {
	Up = "Up",
	Down = "Down",
	Left = "Left",
	Right = "Right",
}

let currentDirection: Direction = Direction.Up; // ok
let currentDirection: Direction = Direction.West; // Property 'West' does not exist on type 'typeof Direction'.

👌Using literal types, you can define and enforce specific values, making your code more EXPLICIT and catching potential errors at compile-time.

Tags 🏷