π€ Solution: TypeScript Generics
Generics allow you to create components, functions, or classes that work with multiple types, while still preserving full type information.
Think of them as:
π "Type placeholders" that get filled in later
Basic example:
function identity<T>(value: T): T {
return value
}
Here:
-
T is a generic type
- It represents whatever type you pass in
Usage:
identity<string>("hello") // string
identity<number>(123) // number
TypeScript automatically knows what comes out based on what goes in.
π’ Practical Examples
Letβs look at real-world scenarios where generics shine.
β
Example 1: Reusable API Response Type
Very common pattern in frontend apps:
type ApiResponse<T> = {
data: T
error: string | null
}
Usage:
type User = {
id: number
name: string
}
const response: ApiResponse<User> = {
data: { id: 1, name: "John" },
error: null
}
Now your API types are consistent, reusable, and fully typed.
β
Example 2: Generic Array Helper
function getFirstItem<T>(arr: T[]): T {
return arr[0]
}
Usage:
const number = getFirstItem([1, 2, 3]) // number
const string = getFirstItem(["a", "b"]) // string
TypeScript knows exactly what type is returned.
β
Example 3: Generic Props in Vue
Check out my other article where I have explained this topic in more details here.
β
Example 4: Constraining Generics
Sometimes you want flexibility β but with rules.
function getLength<T extends { length: number }>(value: T) {
return value.length
}
Usage:
getLength("hello") // β
getLength([1, 2, 3]) // β
getLength(123) // β error
With this approach, you ensure flexibility but also controlled structure.
β
Example 5: Keyof + Generics
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key]
}
Usage:
const user = {
id: 1,
name: "John"
}
getProperty(user, "name") // β
getProperty(user, "age") // β error
This is extremely powerful for forms, dynamic access, or utilities.
π Learn more
If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:
Vue School Link
It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects π
π§ͺ Advance skills
A certification boosts your skills, builds credibility, and opens doors to new opportunities. Whether you're advancing your career or switching paths, it's a smart step toward success.
Check out Certificates.dev by clicking this link or by clicking the image below:
Certificates.dev Link
Invest in yourselfβget certified in Vue.js, JavaScript, Nuxt, Angular, React, and more!
β
Summary
TypeScript Generics are one of the most powerful features in the language. They let you write code that is both flexible and safe β which is exactly what you want in modern applications.
Once you start using them properly, itβs hard to go back.
Take care!
And happy coding as always π₯οΈ