How to check for null value inline and throw an error in typescript?

As long as TypeScript doesn’t support this natively, you could write a function similar to this one:

function throwExpression(errorMessage: string): never {
  throw new Error(errorMessage);
}

which would then allow you to throw an error as expression:

const myString = nullableVariable ?? throwExpression("nullableVariable is null or undefined")

Leave a Comment

tech