◢ This post is also available in: 日本語
Generics allow you to write reusable code that works with multiple types.
function identity<T>(arg: T): T {
return arg
}
const result = identity<string>("hello")
You can constrain generics to specific types:
interface HasLength {
length: number
}
function logLength<T extends HasLength>(arg: T): void {
console.log(arg.length)
}
Generics are one of the most powerful features of TypeScript.