Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullish Coalescing on functions

Tags:

typescript

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"
like image 338
Timon Avatar asked Mar 16 '26 18:03

Timon


1 Answers

If you use optional chaining on your function you could shorten that line to this:

const error = foo.getError?.('...') ?? "No error"
like image 193
Dan Fletcher Avatar answered Mar 22 '26 07:03

Dan Fletcher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!