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

Typescript non-null validation function

Sorry if there are duplicates of this question. I’m having a hard time coming up with search terms that give relevant results.

My use case is that I want to check if a variable is not "empty" or that it is specifically not null, undefined, or an empty string. Like this:


const myVar: string | null | undefined;

if (myVar === null || myVar === undefined || myVar.trim() === '') return;

const nonNullVar: string = myVar;

Typescript is smart enough to know that if the code gets passed the if check, then myVar is definitely a string. However, I would like to do this check multiple times, so I wrote a function for it:

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

function isEmpty(val: string | null | undefined) {
    return val === null || val === undefined || val.trim() === '';
}

// ...

const myVar: string | null | undefined;

if (isEmpty(myVar)) return;

const nonNullVar: string = myVar;

But typescript is no longer able to infer that myVar is not empty, so it throws an error.

Does typescript have some way to signify that my method ensures non-nullness? I know I can use a non-null assertion (!), but I’m trying to avoid disabling the eslint rule for it as I don’t want my team using it as a work around for actually checking their variables.

>Solution :

Type it as follows:

function isEmpty(val: string | null | undefined): val is null|undefined {
  return val === null || val === undefined || val.trim() === ''; 
}

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

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