4 ms·
What do you mean? Without any special annotations, TS already understands that function test(x: number | string): void { x.toUpperCase(); } i
by anderskaseorg 7y ago
What do you mean? Without any special annotations, TS already understands that
function test(x: number | string): void {
x.toUpperCase();
}
is an error and
function test(x: number | string): void {
if (typeof x === "number")
throw new Error();
x.toUpperCase();
}
is not. So it should just as easily be able to understand that
function assertIsString(x: number | string): asserts x is string {
}
is an error and
function assertIsString(x: number | string): asserts x is string {
if (typeof x === "number")
throw new Error();
}
is not.
- VMG 7y agoif TS can recognize the difference between the last two, why have an `asserts` annotation at all?
- anderskaseorg 7y agoSo 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.