Learning
TypeScript

Generics alapok

Generikus függvények és típusparaméterek: identity, tömbös példák, keyof, generic interface-ek és constraint-ek.

Generics alapok

Miért kell?

function identityAny(value: any): any {
  return value
}

Generics-szel megmarad a típus:

function identity<T>(value: T): T {
  return value
}

const result1 = identity("hello")
const result2 = identity(42)

Tömbös példa

function firstElement<T>(arr: T[]): T | undefined {
  return arr[0]
}

keyof + constraint

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key]
}

Generic interface

interface ApiResponse<T> {
  data: T
  status: number
  message: string
}

Típusmegszorítások

function printName<T extends { name: string }>(item: T): void {
  console.log(item.name)
}

On this page