3 ms·
So that one can extract out a repeated check such as if (typeof x === "number") throw new Error(); into a function.
by anderskaseorg 7y ago
So that one can extract out a repeated check such as
if (typeof x === "number")
throw new Error();
into a function.
- reissbaker 7y agoI think the thrust of the question is: why can't TypeScript automatically infer the assertion, rather than needing to write out a special annotation on the function?
- anderskaseorg 7y agoIt could, but as a design decision, TS never infers function types based on function bodies, to keep inference more local and predictable. You're expected to specify argument and return types from outside (and TS will then check the body against them). So it's reasonable to expect you to specify assertion types from outside (and TS should then check the body against them).
- VMG 7y agoFair point. In that context your question makes sense.
- reissbaker 7y agoThis is incorrect: TypeScript doesn't require annotating functions with return types, and can infer return types from function bodies. It doesn't infer argument types, but it does infer return types.
- anderskaseorg 7y agoYou’re right, I must have been misremembering from a bug where return type inference was failing. So yeah, TypeScript doesn’t but perhaps should infer assertion signatures where a return type is not specified. However, it would be bad if people who do want to specify the return type were unable to do so, so an `asserts` annotation syntax would still need to be available.