Sobes.tech
Middle+

/* Scrivi il tipo MyRequired — rende tutti i campi opzionali obbligatori */ 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 AI

Risposta dell'AI

Il tipo MyRequired<T> può essere implementato usando i tipi mappati in TypeScript, rimuovendo il modificatore ? da tutte le proprietà di T. Questo si fa usando l'operatore -? prima della chiave della proprietà:

// Rimuove l'opzionalità da tutte le proprietà

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

// Esempio di utilizzo

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

const user1: MyRequired<User> = { id: 1, name: "John" } // corretto
const user2: MyRequired<User> = { id: 1 } // errore, manca la proprietà obbligatoria name