How can I ensure an object includes some specific fields using Partial<>?

4.2k Views Asked by At

I have a function with the following parameter:

const handleAccount = (
  account: Partial<IAccountDocument>,
  ...
) => { ... }

In no way can I change the interface for IAccountDocument to not require certain fields, i.e. I must use Partial<>. How can I make it so that IAccountDocument has specific fields included whilst also being allowed to be partially created?

2

There are 2 best solutions below

6
Tobias S. On

Use the Pick utility type to choose some mandatory properties and combine it with Partial<IAccountDocument>.

// Let's say that a and b must be mandatory properties
interface IAccountDocument {
  a: number 
  b: number
  c: number
  d: number
  e: number
}

const handleAccount = (
  account: Pick<IAccountDocument, "a" | "b"> & Partial<IAccountDocument>
) => {}


// valid
handleAccount({a: 123, b: 123, c: 123})

// not valid
handleAccount({c: 23})
0
Zoom On

Typescript supports intersection types.

Borrowing from the answer by tobias-s:

// Let's say that a and b must be mandatory properties
type IAccountDocument {
  a: number 
  b: number
  c: number
  d: number
  e: number
}

type CustomPartialIAccountDocument = Partial<IAccountDocument> & {
  a: number 
  b: number
}

// valid
CustomPartialIAccountDocument ({a: 123, b: 123, c: 123})

// not valid
CustomPartialIAccountDocument ({c: 23})