How can I make one property non-optional in a typescript type?

If you check the source for the Required type, it’s this:

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

The same syntax can be used to construct a generic type that will give you what you want:

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

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

type UserWithName = WithRequired<User, 'name'>

// error: missing name
const user: UserWithName = {
  id: '12345',
}

Playground link

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)