I have an interface
interface Foo {
error?: string;
getError?: (param: any) => string
}
Let's say we always want to call the function, but there is the possibility of it being undefined. For base types we could use ??:
const error = foo.error ?? "No Error";
foo.getError(...) will throw ... is not a function which is understandable if there is none :=)
So, is there an equivalent or elegant alternative to the nullish coalescing operator on functions or do I always have to do something like this:
const error = foo.getError ? foo.getError(...) ?? "No error" : "No error"
If you use optional chaining on your function you could shorten that line to this:
const error = foo.getError?.('...') ?? "No error"
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