Vladyslav Zavalykhatko
Vladyslav Zavalykhatko

Reputation: 17384

How to make specific props non-nullable in Typescript?

I have a type:

type Item = {
  cost: number | null
  name: string
  date: string | null
  rating: number | null
}

Is there a way in TS to create a type based on Item, which would have date and rating NonNullable? I could do something like this:

  type FullItem = Omit<Item, 'date' | 'rating'> & {
    date: NonNullable<Item['date']>
    rating: NonNullable<Item['rating']>
  }

but it seems a bit cumbersome.

Upvotes: 17

Views: 12380

Answers (2)

Vladyslav Zavalykhatko
Vladyslav Zavalykhatko

Reputation: 17384

Ok, I just came up with a solution it seems:

type RequiredNotNull<T> = {
  [P in keyof T]: NonNullable<T[P]>
}

type Ensure<T, K extends keyof T> = T & RequiredNotNull<Pick<T, K>>

type Item = {
  cost: number | null
  name: string
  date: string | null
  rating: number | null
}

type FullItem = Ensure<Item, 'rating' | 'date'>

Upvotes: 34

T.J. Crowder
T.J. Crowder

Reputation: 1074495

You don't need the Omit:

type FullItem = Item & {
    date: NonNullable<Item["date"]>;
    rating: NonNullable<Item["rating"]>;
}

or of course, if you don't mind repeating the types:

type FullItem = Item & {
    date: string;
    rating: number;
}

If you changed Item later such that the types didn't match, the result would be a member with never which I'm guessing would fairly quickly show up and get dealt with. :-)

Upvotes: 5

Related Questions