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.
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.
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/oguz279 Nov 10 '20
I prefer typeof fn === "function" && fn() as it covers cases where fn would have a truthy value but not be a function.