Make only part of Typescript properties required

Making all properties of a type or an interface required is easy, thanks to the Required TypeScript utility. But sometimes, it can be useful to make only part of the optional properties required.

For example, let's take this type User

type User = {
  id: string
  name?: string
  email: string
  phoneNumber?: string
}

const user: User = { id: uuid(), email: '[email protected]' } // Will not throw any type error

Now, we want to enforce that the name will exist in the User type. If we use the Required utility, the phoneNumber property will be required as well. So we will need to create a new type to enforce only the name property to be required.

To do so, let's take the Required utility as an example:

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

type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] }

Now we can just make part of the properties required.

const userWithError: WithRequired<User, 'name'> = {
  id: uuid(),
  email: '[email protected]',
} // will throw an error
const userWithoutError: WithRequired<User, 'name'> = {
  id: uuid(),
  email: '[email protected]',
  name: 'John Smith',
} // will not throw an error

Consulting

If you're seeking solutions to a problem or need expert advice, I'm here to help! Don't hesitate to book a call with me for a consulting session. Let's discuss your situation and find the best solution together.

Share this post
Follow the RSS feed