TypeScript Generics yaj
Generics feature ghaH. basic TypeScript types yaj qaSDI' Qagh, 'ej yaj vaj tool lo'lu' law'. yIch: function pagh type wa' type vaD ghItlh pagh, "type nob Hoch" vaD ghItlh, 'ej TypeScript type track signature Daq.
generics Qagh Qotlh
array wa'DIch element nob function neH.
function firstOfNumbers(arr: number[]): number {
return arr[0];
}
function firstOfStrings(arr: string[]): string {
return arr[0];
}
cha' functions, logic rap, types pIm. any lo' laH:
function first(arr: any[]): any {
return arr[0];
}
Qu' 'ach information Hoch Qaw'. first([1, 2, 3]) any type (number pagh) - first([1, 2, 3]).toUpperCase() Qagh Qaw' pagh.
Generics input type output type connection Dach:
function first<T>(arr: T[]): T {
return arr[0];
}
const n = first([1, 2, 3]); // T inferred as number, n: number
const s = first(['a', 'b', 'c']); // T inferred as string, s: string
T type parameter ghaH - placeholder, TypeScript nob value Daq fill (function parameter rap). first<number>([1, 2, 3]) ghItlh poQ pagh; TypeScript T argument vo' infer.
T nuq laH constrain
unconstrained T Hoch laH - shape Sov pagh. compile pagh:
function getLength<T>(item: T): number {
return item.length; // Error: Property 'length' does not exist on type 'T'
}
TypeScript jatlh Dun - T number laH, .length pagh. extends constrain:
function getLength<T extends { length: number }>(item: T): number {
return item.length; // OK — T is guaranteed to have a `length` property
}
getLength('hello'); // OK, strings have .length
getLength([1, 2, 3]); // OK, arrays have .length
getLength(42); // Error: number doesn't satisfy the constraint
extends class inheritance pagh - "T shape assignable". .length number property ghaj type Hoch Dun.
generic interfaces 'ej classes
Generics functions neH pagh - types parameterize. Box<T> wa' value hold:
interface Box<T> {
value: T;
}
const numberBox: Box<number> = { value: 42 };
const stringBox: Box<string> = { value: 'hello' };
real example - typed API response wrapper:
interface ApiResponse<T> {
data: T;
status: number;
error: string | null;
}
async function fetchUser(id: string): Promise<ApiResponse<User>> {
const res = await fetch(`/api/users/${id}`);
const data = await res.json();
return { data, status: res.status, error: null };
}
fetchUser caller Hoch response.data User type tlhap (any pagh) - generic payload type response shape Daq carry. UserApiResponse, PostApiResponse entity Hoch ghItlh poQ pagh.
type parameters law'
Generics wa' parameter law' laH - cha' independent Dochmey combine function Daq. map function misvam:
function mapArray<T, U>(arr: T[], fn: (item: T) => U): U[] {
return arr.map(fn);
}
const lengths = mapArray(['a', 'bb', 'ccc'], (s) => s.length);
// T inferred as string, U inferred as number
// lengths: number[]
T input element type, U callback nob. rap poQ pagh. TypeScript cha' independent infer.
default type parameters
default function parameters rap, generics defaults ghaj. type parameter reH rap 'ach override laH:
interface PaginatedResponse<T = unknown> {
items: T[];
page: number;
totalPages: number;
}
function emptyPage(): PaginatedResponse {
return { items: [], page: 1, totalPages: 1 }; // T defaults to unknown
}
function usersPage(): PaginatedResponse<User> {
return { items: [], page: 1, totalPages: 1 }; // T explicitly User
}
Qagh: generics poH Dung lo'
function Hoch generic poQ pagh. function string neH Qu' vaj function process<T extends string>(input: T) type parameter chel (choH pagh, complexity Dun pagh). Generics Dun input output type relationship preserve poQ: first<T> same element type nob, Box<T> arbitrary values wrap, mapArray<T, U> type choH. type choH pagh vaj concrete type Dun.
yaj
Generics type relationship preserve (any Qaw', N overloads duplicate). mental model: type parameter parameter ghaH (function argument rap), type nob, TypeScript signature Daq track (value rap).