Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Helper function eg. is-empty needs to change type

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Your function needs a type predicate.

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

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading