Sobes.tech
Middle+

/* Írja meg a MyRequired típust — teszi kötelezővé minden opcionális mezőt */ type User = { id?: number name?: string } type MyRequired<T> = { } const user1: MyRequired<User> = { id: 1, name: "John" } const user2: MyRequired<User> = { id: 1 }

sobes.tech MI

Válasz az MI-től

A MyRequired<T> típus TypeScript-ben használható mapped types segítségével, eltávolítva a ? módosítót T összes tulajdonságából. Ez a -? operátor használatával történik a tulajdonság kulcsa előtt:

// Az összes tulajdonság opcionális jelölésének eltávolítása

type MyRequired<T> = {
  [P in keyof T]-?: T[P]
}

// Használati példa

type User = {
  id?: number
  name?: string
}

const user1: MyRequired<User> = { id: 1, name: "John" } // helyes
const user2: MyRequired<User> = { id: 1 } // hiba, hiányzik a kötelező name mező