Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

TS
TypeScript
0/10 completed
Beginner
Why TypeScript?Basic types and inferenceTyping functionsObjects, interfaces and type aliases
Intermediate
Unions and narrowingLiteral types, tuples and enumsGenerics
Advanced
Utility typesMapped and conditional types
Pro
TypeScript in real projects
Tracks / TypeScript / Intermediate

Literal types, tuples and enums

TypeScript can be much more precise than "any string" or "any array". These tools let you say exactly which values are allowed.

Literal types

A literal type is a single exact value. Combine literals with | to create a fixed set of allowed values:

TypeScript · editable

This is far safer than accepting any string and hoping callers spell it right.

const and literal inference

TypeScript · editable

as const plus typeof X[number] is a popular trick: you write the list once and get both a runtime array (for dropdowns or validation) and a type.

Template literal types

Build string types from other types:

TypeScript · editable

Tuples: fixed-length arrays

A tuple is an array with a known length and a known type at each position:

TypeScript · editable

Enums

Enums define named constants. They're one of the few TypeScript features that generate runtime code:

TypeScript · editable

Open "View the compiled JavaScript" to see the object that the enum becomes.

Should you use enums?

Many TypeScript teams prefer literal unions or as const objects instead:

TypeScript · editable
String enum Literal union as const object
Runtime value ✓ ✗ ✓
Plain strings accepted ('pending') ✗ (must use Status.Pending) ✓ ✓
Works with "type-stripping" tools (Node's built-in TS support, erasableSyntaxOnly) ✗ ✓ ✓

Avoid numeric enums (enum Dir { Up, Down }). They accept any number, which undermines type safety.

Practice

  1. Create a Weekday literal union and a function isWeekend(day: Weekday): boolean.
  2. Create a tuple type RGB of three numbers and a function toHex(color: RGB): string.
  3. Create const SIZES = ['S', 'M', 'L', 'XL'] as const and derive a Size type from it.
TypeScript · editable
✎ Check your understanding

1.What type does const status = 'active' have?

2.What does as const do to an object literal?

← Unions and narrowing