The interface I am working with is defined below:
interface Foo {
error?: string;
getError?: (param: any) => string
}
In this scenario, we always need to call the function getError
, but it may be undefined. When dealing with base types, we can use the nullish coalescing operator ??
:
const error = foo.error ?? "No Error";
Attempting to call foo.getError(...)
could result in a ... is not a function error message, which makes sense if the function doesn't exist.
My question is, is there an equivalent or more elegant way to handle this situation without having to resort to something like this every time:
const error = foo.getError ? foo.getError(...) ?? "No error" : "No error"