In C# I can write code to check for null references and in case throw a custom exception, example:
var myValue = (someObject?.SomeProperty ?? throw new Exception("...")).SomeProperty;
In recent updates TypeScript introduced the null coalescing operator ?? but using it like the above statement produces a compilation error. Is there some similar allowed syntax in TypeScript?
To clarify, the desired behavior is achieved with the following code:
if(someObject?.someProperty == null) {
throw new Error("...");
}
var myValue = someObject.someProperty.someProperty;
The code:
var myValue = someObject?.someProperty.someProperty;
works logically ok but throws a less meaningful exception.
To declare a function that throws an error, set its return type to never . The never type is used for functions that never return a value, in other words functions that throw an exception or terminate execution of the program.
We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.
In Typescript to enforce strict null checks in tsconfig.json file, we need to enable “strictNullChecks” t o true. When “strictNullChecks” is false, the language generally ignores variables of type null and undefined. If null and undefined is used in places where a definite value is expected, it raises an error.
The typescript implements the same in the 3.7 version. These both are checked for null and undefined values. Optional Chaining operator : The symbol is ?, is used to check the account is null or undefined, It will return id if an account is not null or undefined, else return undefined. To check in javascript or jquery , use typeof operator.
Note that the check for nullish should be defined like this: function isNullish<T>(value: T | undefined | null): value is undefined | null { return <T>value === undefined || <T>value === null; } – Kfir Dadosh Sep 23 at 13:42 Add a comment | 15 if(data){}
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); } const myString = nullableVariable ?? throwExpression ("nullableVariable is null or undefined")
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")
The reason for the syntax error is that throw
is a statement, so you can't use it as the operand to an operator.
There is a JavaScript proposal for throw
expressions working its way through the TC39 process, currently at Stage 2. If it gets to Stage 3 you can expect it will show up in TypeScript soon thereafter. (Update at the end of 2020: However, it seems to have stalled, having been blocked in Jan 2018 by a TC39 member who didn't think they "...were sufficiently motivated if we have do
expressions..." Note that do
expressions are still Stage 1 here at the end of 2020, but at least they were presented to TC39 in June.)
With a throw
expression, you could write this (if you want the value of someObject.someProperty
):
const myValue = someObject?.someProperty ?? throw new Error("custom error here");
Or if you want someObject.someProperty.someProperty
(which is what I think your C# version does):
const myValue = (someObject?.someProperty ?? throw new Error("custom error here")).someProperty;
There's a Babel plugin for it you can use now. Here's the first example above on Babel's REPL.
Side note: You've said you want to throw a custom error, but for anyone else reading this who doesn't need a custom error:
If you want someObject.someProperty.someProperty
, with no error if someObject
is null
/undefined
but getting an error if someObject.someProperty
is null
/undefined
, you can do:
const myValue = someObject?.someProperty.someProperty;
With that:
someObject
is null
or undefined
, myValue
will get the value undefined
someObject
is not null
or undefined
but someObject.someProperty
is null
or undefined
, you'll get an error because we didn't use ?.
after the first someProperty
.someObject
and someObject.someProperty
are both not null
or undefined
, myValue
will get the result of looking up someObject.someProperty.someProperty
.If you're interested in throwing the error within a single line, you could wrap it in an immediately invoked function expression:
const test = null ?? (() => {throw new Error("Test is nullish")})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With