Consider the code below (running in TypeScript 3.2.2):
const status: 'successful' | 'failed' = 'successful';
function test(): typeof status {
const status = 'hello';
return 'successful';
}
This doesn't compile since the return type of test and its signature do not match:
error TS2322: Type '"successful"' is not assignable to type 'IResult<"hello">'.
For some reason the status definition inside the function is being used to determine the return type.
This doesn't happen when using var; this code:
function test(): typeof status {
var status = 'hello'; // notice the var here
return 'successful';
}
produces the expected return type of 'successful' | 'failed'.
Using let:
function test(): typeof status {
let status = 'hello'; // notice the let here
return 'successful';
}
This compiles but with the effect that the return type is string, the inner definition is being used again.
I expected tsc to use the status which is defined most high up in scopes to evaluate its return type in both cases, regardless of what declarations exist inside test. Why is the behaviour as observed above? This should be related to how tsc decides which variables to use for type inference.