DEV Community

Discussion on: Advanced TypeScript Types cheat sheet (with examples)

Collapse
 
khrisl33t profile image
kHRISl33t

A really well-written article with good examples. Good job!

Would like to add one more thing I like to use and you might find it interesting:

type Maybe<T> = T | null;

function foo(bar: Maybe<string>) {
  if (!bar) {
    // handle if bar is null
  }
  // do stuff if value not null.
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
chico1992 profile image
chico1992

You should explicitly check for bar===null as in your case the empty string will also make !bar true

Collapse
 
khrisl33t profile image
kHRISl33t

you are right, thanks :)

Collapse
 
ionellupu profile image
Ionel Cristian Lupu

What are some really good real world examples for this? (3,4 examples).

Wouldn't the optional operator be enough?

function foo(bar?: string) {
  if (!bar) {
    // handle if bar is falsy
  }
  // do stuff if value not falsy.
}
Enter fullscreen mode Exit fullscreen mode

The only thing I can think of is when you really need the parameter to be exactly null. But I never have this use case in the projects I work on, so I think something is fishy :))

Collapse
 
khrisl33t profile image
kHRISl33t

Actually it's just personal preference to have null values instead of undefined.
The example I provided is actually not that great, because I tend to use this more with objects and their properties.

Collapse
 
michaeljota profile image
Michael De Abreu

The difference between the two, is that in Maybe the value is required, and in the second one is optional. So, you can have Maybe values and those values would be either defined or not, but would still be required. I have found this to be useful in React.