TypeScript Generics
TypeScript generics let you write code that works with many types while keeping full type information. Without generics, you either repeat code for each type or fall back to any, which loses safety. With generics, one function or class can serve strings, numbers, and custom objects without giving up checks.
This tutorial covers the problem generics solve, generic functions with <T>, explicit type arguments versus inference, generic interfaces and classes, constraints with extends, the keyof operator, default type parameters, and multiple type parameters. You will also see the common mistake of reaching for any when a generic is the right tool.
What Are TypeScript Generics?
TypeScript generics are type parameters that let a function, interface, or class work with a type supplied later. You write them in angle brackets, like <T>. The compiler fills in the actual type at each call site, so the code stays reusable and fully checked.
Here is a simple example:
function identity<T>(value: T): T {
return value;
}
console.log(identity("hello"));
console.log(identity(42));
// Output: hello
// Output: 42
The T is a placeholder. When you call identity("hello"), T becomes string. When you call identity(42), T becomes number. The return type matches the argument type exactly.
What Problem Do Generics Solve?
Without generics, you face a trade-off. You can write one function per type, which repeats logic. Or you can use any, which works for all types but throws away type information. Generics give you the reuse of any with the safety of specific types.
function firstAny(items: any[]): any {
return items[0];
}
function first<T>(items: T[]): T {
return items[0];
}
const a = firstAny(["x", "y"]);
const b = first(["x", "y"]);
console.log(a.toUpperCase());
console.log(b.toUpperCase());
console.log(b);
// Output: X
// Output: X
// Output: x
How it works: firstAny returns any, so the compiler does not know the result is a string. first returns T, and when called with string[], T is string, so b is a string. Both calls to toUpperCase compile here, but only the generic version would catch a mistake like b.toFixed(), because b is a string, not a number.
How Do Generic Functions Work with Explicit Type Arguments and Inference?
TypeScript can infer the type argument from the arguments you pass, or you can supply it explicitly in angle brackets after the function name. Inference keeps calls short. Explicit arguments are useful when the compiler cannot infer, or when you want to force a specific type.
function pair<A, B>(first: A, second: B): [A, B] {
return [first, second];
}
const inferred = pair("age", 28);
const explicit = pair<string, number>("age", 28);
console.log(inferred);
console.log(explicit);
// Output: [ 'age', 28 ]
// Output: [ 'age', 28 ]
How it works: In inferred, the compiler reads "age" as a string and 28 as a number, so A is string and B is number. In explicit, you state the types directly. Both produce the same tuple type. Prefer inference when it is clear, and use explicit arguments when you need to guide the compiler or document intent.
How Do Generic Interfaces and Classes Work?
An interface or class can take type parameters, making it reusable across element types. A generic interface describes a shape that depends on T, and a generic class stores or manipulates values of T. These are common in data structures and API clients.
interface Box<T> {
value: T;
}
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
size(): number {
return this.items.length;
}
}
const numbers = new Stack<number>();
numbers.push(1);
numbers.push(2);
console.log(numbers.pop());
const strings = new Stack<string>();
strings.push("a");
console.log(strings.size());
// Output: 2
// Output: 1
How it works: The Box<T> interface describes an object with a value of type T. The Stack<T> class stores an array of T. When you write new Stack<number>(), every method is typed for numbers, so push("x") would fail. The pop method returns T | undefined because the stack may be empty, which is a realistic and safe signature.
How Do Constraints Work with extends?
A constraint limits which types a type parameter can accept. You write T extends SomeType. Inside the generic, you can then use properties or methods that SomeType guarantees. This is how you write a generic that needs a specific shape.
type HasLength = { length: number };
function logLength<T extends HasLength>(value: T): void {
console.log(`Length: ${value.length}`);
}
logLength("hello");
logLength([1, 2, 3]);
// logLength(42);
// Error: Argument of type 'number' is not assignable to parameter of type 'HasLength'.
// Output: Length: 5
// Output: Length: 3
How it works: T extends HasLength means "any type that has a length number property." Strings and arrays both satisfy this, so both calls compile. A number does not, so the compiler rejects it. The constraint lets the function use value.length safely, because every valid T is known to have it.
How Does keyof Work with Generics?
The keyof operator produces a union of a type's property names. Combined with generics, it lets you write a function that safely reads any property of an object. The result type is inferred from the key you pass.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: "Riya", age: 28, active: true };
const name = getProperty(user, "name");
const age = getProperty(user, "age");
console.log(name, age);
// getProperty(user, "email");
// Error: Argument of type '"email"' is not assignable to parameter of type '"name" | "age" | "active"'.
// Output: Riya 28
How it works: K extends keyof T restricts the key to valid property names. T[K] is an indexed access type that returns the type of that property. So getProperty(user, "name") returns a string, and getProperty(user, "age") returns a number. Passing "email" fails because it is not a key of user. This pattern is the basis of many utility functions and libraries.
What Are Default Type Parameters and Multiple Type Parameters?
A default type parameter gives a fallback type when the caller does not specify one. Multiple type parameters let a single generic work with several types at once. Both make generic APIs easier to use without losing flexibility.
interface ApiResponse<T, E = string> {
data: T | null;
error: E | null;
}
const ok: ApiResponse<{ id: number }> = { data: { id: 1 }, error: null };
const fail: ApiResponse<{ id: number }, { code: number }> = {
data: null,
error: { code: 404 },
};
console.log(ok.data);
console.log(fail.error);
// Output: { id: 1 }
// Output: { code: 404 }
How it works: ApiResponse has two parameters. T is required and describes the success data. E defaults to string for errors. The ok value uses the default, so error is string | null. The fail value provides a custom error type, so error is { code: number } | null. Defaults reduce verbosity while preserving precision.
Generics vs any: How Do They Compare?
| Feature | Generic <T> |
any |
|---|---|---|
| Type information preserved | Yes | No |
| Autocomplete on result | Yes | No |
| Errors caught at compile time | Yes | No |
| Code reuse across types | Yes | Yes |
| Recommended for new code | Yes | No |
The common mistake is reaching for any when a generic would work. any silences the compiler, but the generic keeps the checks. In the TypeScript Any, Unknown & Never tutorial, you saw how any moves errors to runtime. Generics keep them at compile time.
Common Mistakes and Best Practices
- Using
anyinstead of a generic. This removes type safety and autocomplete. If a function works with many types but returns the same type, a generic is almost always the right choice. - Adding too many type parameters. A function with
<A, B, C, D>is hard to call and read. Start with one, add more only when the API genuinely needs them, and use defaults to reduce noise. - Forgetting constraints when accessing properties.
Talone has no known properties. If you needvalue.length, addT extends { length: number }so the compiler allows it. - Writing explicit type arguments when inference works.
identity<string>("x")is noisy whenidentity("x")infers the same thing. Use explicit arguments only when they add clarity or are required. - Confusing
keyofwith a value.keyof Tis a type, not a runtime list. To loop over keys at runtime, useObject.keys, which returnsstring[]and needs its own typing strategy.
Real-World Example: Identity, Stack, and Safe Property Access
This example combines a generic identity function, a Stack<T> class, and getProperty<T, K extends keyof T>.
function identity<T>(value: T): T {
return value;
}
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
peek(): T | undefined {
return this.items[this.items.length - 1];
}
size(): number {
return this.items.length;
}
}
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const stack = new Stack<number>();
stack.push(10);
stack.push(20);
const top = stack.peek();
const user = { name: "Arjun", age: 32, city: "Pune" };
const city = getProperty(user, "city");
const echoed = identity("done");
console.log(top, stack.size());
console.log(city);
console.log(echoed);
// Output: 20 2
// Output: Pune
// Output: done
How it works, line by line. identity<T> returns exactly what it receives, so echoed is a string. Stack<number> stores a numeric array. push(10) and push(20) add numbers, and TypeScript rejects any other type. peek returns T | undefined because the stack could be empty, so top is number | undefined. getProperty takes an object and a key that must be one of its properties. The key "city" is valid, so the return type is string, and city is a string. If you wrote getProperty(user, "email"), the compiler would reject it because "email" is not a key of user. The identity call shows how inference makes the call short while keeping the exact type.
Summary
- TypeScript generics let functions, interfaces, and classes work with many types while keeping full type information.
- Write generic functions with
<T>; TypeScript infers the type or you pass it explicitly. - Generic interfaces and classes like
Box<T>andStack<T>reuse structure across element types. - Constraints with
extendslimit allowed types and unlock property access inside the generic. keyofwithgetProperty<T, K extends keyof T>gives type-safe property access.- Default type parameters reduce noise, and multiple parameters handle pairs of types.
- Prefer generics over
anyso mistakes stay at compile time.
Now that you can write reusable generic code, continue to the TypeScript Utility Types tutorial to learn built-in helpers like Partial, Pick, and Record that work hand in hand with generics.
Frequently Asked Questions
When should I use a generic instead of any?
Use a generic when the function or class should work with many types but preserve the relationship between input and output. If the output type depends on the input type, a generic keeps that link. Use any only as a last resort for legacy code, because it removes all checks and autocomplete.
Can a generic have more than one type parameter?
Yes. Write <A, B> to declare two parameters, and the compiler infers or you pass both. Multiple parameters are useful for pairs, maps, and APIs with separate success and error types. Keep the count small so the signature stays readable.
What does T extends keyof T mean in getProperty?
K extends keyof T restricts K to the property names of T. Combined with the return type T[K], it means the function returns the type of the chosen property. This gives type-safe access: valid keys are allowed, invalid keys are rejected, and the result type matches the key.
Can generic type parameters have default values?
Yes. Write <T = string> to give T a default. If the caller does not specify a type, the default is used. Defaults are useful in APIs where most callers want a common type but a few need a custom one, such as an error type defaulting to string.
Do generics exist at runtime?
No. Type parameters are erased during compilation, just like other TypeScript types. The compiled JavaScript contains no <T> and no type arguments. Generics are a compile-time tool for safety and reuse; they do not change the runtime behavior of your code.
Practice Exercises
Exercise 1 (Easy): Write a Generic Identity Function
Write a function echo<T>(value: T): T that returns its argument. Call it with a string and a number.
Show solution
function echo<T>(value: T): T {
return value;
}
console.log(echo("hi"));
console.log(echo(7));
// Output: hi
// Output: 7
Inference sets T to string for the first call and number for the second, so the return type matches each argument.
Exercise 2 (Easy): Generic Array Helper
Write a function last<T>(items: T[]): T | undefined that returns the last item or undefined. Call it with a number array and a string array.
Show solution
function last<T>(items: T[]): T | undefined {
return items[items.length - 1];
}
console.log(last([1, 2, 3]));
console.log(last(["a", "b"]));
console.log(last([] as number[]));
// Output: 3
// Output: b
// Output: undefined
The return type T | undefined is honest about the empty-array case, and the generic keeps the element type for each call.
Exercise 3 (Medium): Generic Stack Class
Create a class Box<T> with add(item: T), get(): T | undefined, and size(). Use it with strings.
Show solution
class Box<T> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
get(): T | undefined {
return this.items[0];
}
size(): number {
return this.items.length;
}
}
const b = new Box<string>();
b.add("first");
b.add("second");
console.log(b.get(), b.size());
// Output: first 2
Box<string> restricts add and get to strings, so passing a number would be a compile error.
Exercise 4 (Challenge): Constraint and keyof
Write a function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] that returns the values of a key from every item. Use it on an array of users.
Show solution
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const users = [
{ name: "Riya", age: 28 },
{ name: "Arjun", age: 32 },
];
console.log(pluck(users, "name"));
console.log(pluck(users, "age"));
// pluck(users, "email");
// Error: Argument of type '"email"' is not assignable to parameter of type '"name" | "age"'.
// Output: [ 'Riya', 'Arjun' ]
// Output: [ 28, 32 ]
K extends keyof T restricts the key to real properties, and T[K][] gives the correct array type for each key.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
