r/node • • Nov 10 '20

Conditionally call a function with optional chaining.

Post image
345 Upvotes

126 comments sorted by

View all comments

Show parent comments

10

u/oguz279 Nov 10 '20

Yep. And that's why kids, always use Typescript ❤️

2

u/LucasCarioca Nov 10 '20

Typescript is wonderful for preventing this ugly code

1

u/Miridius Nov 10 '20

Typescript doesn't add runtime type checks, you still have to do that yourself if you're accepting multiple types (in this case function | undefined). So no.

1

u/LucasCarioca Nov 10 '20

Which is something that should be avoided. And if you can’t avoid it then you should use an optional. Which would clearly solve that typeof mess that I was referring to. So yes.

0

u/Miridius Nov 10 '20

If you're talking about optional as in just using the "?." operator as OP showed then yes I agree with you.

But typescript won't stop there from ever being a truthy value where you expect a function because the value can come from outside your codebase in a place with missing, vague, or incorrect types - when you use a library or someone else uses your library

1

u/LucasCarioca Nov 10 '20

Dude look at the start of this thread... I’m replying to that piece of code....