Home > Software engineering >  Typescript non-null validation function
Typescript non-null validation function

Time:08-02

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:

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.

CodePudding user response:

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

  • Related