Multiple Type Parameters in Classes
What You'll Learn
You'll learn how to define classes with two or more type parameters, giving you maximum flexibility when different properties or methods need independently typed data.
Why Multiple Type Parameters?
Sometimes a single generic isn't enough. Imagine a class that pairs two values together—like a key-value store, or a tuple wrapper. The key might be a string while the value is a number, or both could be custom types. Rather than forcing them to share one type parameter, you can give each its own.
Think of it like a storage box with two separate compartments, each holding a different kind of item. You wouldn't want to force both compartments to hold the same type of object—that defeats the purpose of flexibility.
Basic Syntax
class Pair<K, V> {
constructor(public key: K, public value: V) {}
getKey(): K {
return this.key;
}
getValue(): V {
return this.value;
}
}
Here, K represents the key type and V represents the value type. They're completely independent.
Using the Class
const stringNumberPair = new Pair<string, number>("age", 30);
const booleanArrayPair = new Pair<boolean, string[]>(true, ["a", "b"]);
stringNumberPair.getKey(); // string
stringNumberPair.getValue(); // number
TypeScript infers both types from the arguments, or you can specify them explicitly.
Why This Matters
Multiple type parameters let you model relationships between different data types without losing type safety. They're essential for containers, mappers, result wrappers, and anywhere you need independent typed properties or methods in the same class.
Key Takeaway: Classes can accept multiple type parameters (e.g., <K, V, T>), allowing each property or method to use different independent types while maintaining full type safety.