Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make specific props non-nullable in Typescript?

Tags:

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.

like image 316
Vladyslav Zavalykhatko Avatar asked Dec 11 '25 10:12

Vladyslav Zavalykhatko


2 Answers

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'>
like image 108
Vladyslav Zavalykhatko Avatar answered Dec 14 '25 09:12

Vladyslav Zavalykhatko


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. :-)

like image 23
T.J. Crowder Avatar answered Dec 14 '25 07:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!