What are Generics ?
Generics in Typescript are a language feature that allows fr creating reusable and type-safe code by introducing placeholders for types. In other words, generics allow functions, classes and interfaces to work with a variety of types without losing type safety.
In typescript, generic types are defined using angle brackets and a type parameter name. For example, the following function takes a type parameter T and returns an array of that type.
Example
The type parameter T can be any type, such as number, string, or a custom type. When calling the function, the type parameter is specified within angle brackets.
function create<T>(num: number): T[] {
const arrays: T[] = T
arrays.push(num)
return arrays;
}
const arr = create<number>(1);
Generics can be used to define types for complex data structures. For example, the following interfaces defines a generic dictionary with keys of type string and values of type T:
interface Dictionary<T> {
[key: string]: T
}
const myDict: Dictionary<number> = {
avid: 1,
cool: 3
}
Generics can be constrained to a specific set of types using the extends keyword. For example, the following function takes an object with a “name” property of type string and returns a greeting:
function greet< T extends HasName>(obj: T) {
return `hello ${obj.name}`
}
const dog = {name: 'ginger'}
console.log(greet(dog)
Defining generic types for APIs:
APIs that return data of different types can benefit from generics to ensure type safety. For example, a generic ApiResponse type that encapsulates the data returned by a REST API can be defined as follows.
interface ApiResponse<T>{
data: T,
success: boolean
message?: string
}
Creating type-safe validation functions: Generics can be used to create type-safe validation functions that can validate values of different types. For example, a generic validate function that checks if a value is not null or undefined can be defined as follows:
function validate<T>(value: T): value is NonNullable<T>{
return value !=null
}