Home > database >  Helper function eg. is-empty needs to change type
Helper function eg. is-empty needs to change type

Time:10-06

I encountered a really weird issue in TS.

Imagine we have an optional value?: string then simple check if value exists

if (value == null) {
   return;
}
console.log(typeof value); // string

(we don't care about empty string)

So it means this will ensure the compiler knows that type of optional variable is a string after our check.


If we introduce some helper function let's say isEmpty

function isEmpty(value: any): boolean {
   return value == null;
}

And now if I create exact same setup as before instead of null check we will use our custom helper

if (isEmpty(value)) {
   return;
}
console.log(typeof value); // string | undefined

How can I modify that helper function in order to let the compiler know that value was already tested for possible undefined? I know that its possible to use type casting but then it no longer make sense for me to introduce helper functions like this.

What are your ideas?

Thanks

CodePudding user response:

Your function needs a type predicate.

function isEmpty(value: any): value is null {
   return value == null;
}

Playground

  • Related