HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to TypeScriptBasic TypesUnion & Literal TypesInterfacesTyped FunctionsArrays & TuplesGenerics & Enums
REFERENCE
📖 Overview
🖥️ Basics & Output
🏷️ Types
📐 Interface & Type Alias
🧩 Function
📋 Array & Object Types
🚀 Next
TypeScript›Generics & Enums

Generics & Enums

Type-independent reusable structures (generics <T>) and named constants (enums).

Simple enough for a 5-year-old to understand

Generic ( <T> )

T is a "type placeholder". The actual type is determined when calling the function — making it both safe and flexible.

Example code
1
function ilk<T>(arr: T[]): T {
Works with any type T.
FunctionWorks with any type T.
2
return arr[0];
Returns the first element.
FunctionReturns the first element.
3
}
End.
FunctionEnd.
4
console.log(ilk([10, 20, 30]));
10 (number)
Output / Input10 (number)
5
console.log(ilk(["a", "b"]));
a (string)
Output / Inputa (string)
FunctionOutput / Input
💡 Hint: Generics allow you to write helpers that "work with any type while preserving the type".

About this topic

Generics mean taking a type as a parameter. If a function needs to work with arrays of any type, instead of using `any` and giving up type safety, you use a type variable; the caller specifies which type they are working with, and the return type is determined accordingly.

Generics are the most intimidating yet most useful feature of TypeScript. The idea is actually simple: functions take values, generics take types. By adding constraints, you can also specify what properties you expect the type variable to have.

An Enum defines a fixed set of options. It is one of the rare TypeScript features that generates code at runtime, which is why it is controversial: since string literal unions provide the same safety with zero runtime cost, they are generally preferred in modern code.

What you will learn

  • Writing generic functions
  • Adding type constraints
  • Generic interfaces and classes
  • Default type parameters
  • Defining enums and their behavior
  • Choosing between enums and string literal unions

When to use?

Generics are needed when you are about to repeat the same logic with different types: a cache, a result wrapper, an API client. In code working with a single type, generics are unnecessary complexity.

Enums are preferred only when you need to work with numeric values or if an existing codebase uses them. In new code, a string literal union or an `as const` object is lighter and JSON-compatible.

Common mistakes

Wrong

function first<T>(items: T[]): T {
  return items[0];
}
const value = first([]);
console.log(value.length);

When given an empty array, `T` cannot resolve to anything and the return is `undefined` — but the type doesn't say this. Generics do not guarantee that the array is non-empty; the return type must include `undefined`.

Correct

function first<T>(items: T[]): T | undefined {
  return items[0];
}
const value = first<string>([]);
console.log(value?.length);

Wrong

function getLength<T>(item: T): number {
  return item.length;
}

Since `T` can be any type, it cannot be known whether the `length` property exists; you get the error "Property 'length' does not exist on type 'T'". It is necessary to add a constraint to the type variable.

Correct

function getLength<T extends { length: number }>(item: T): number {
  return item.length;
}

Wrong

enum Status {
  Pending,
  Done,
}
const s: Status = 42;

Numeric enums ACCEPT undefined numbers as well — a well-known security loophole in older TypeScript versions. String-valued enums or string literal unions do not suffer from this problem.

Correct

const Status = {
  Pending: "pending",
  Done: "done",
} as const;
type Status = (typeof Status)[keyof typeof Status];
const s: Status = "pending";

Frequently asked questions

When are generics truly necessary?

When there is a LINK between the type of the input and the type of the output. In a function that takes an array and returns its first element, the return type depends on the input; generics express this link. Without a link, generics add unnecessary complexity.

Should I use enums?

In new code, generally no. Enums generate code at runtime, are incompatible with JSON, and their numeric form leaves gaps in type safety. A string literal union with an `as const` object does the same job lighter and safer.

How do you write a type constraint?

You declare the shape you expect using `extends` after the type variable. This is what makes generics usable: without a constraint you cannot do anything on the type variable, with a constraint you can safely access all properties of that shape.

Summary

Generics mean taking the type as a parameter and are needed when there is a link between the input and output types; constraints make it usable. Enums generate code at runtime and their numeric form is unsafe — in new code, a string literal union with `as const` is preferred.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code