In the below example:
type Foo = () => void;
let a: Foo | undefined = undefined;
const c = () => { a = () => console.log("Hi!") };
c();
if (a) {
a();
}
At line 4 the type of a is let a: Foo | undefined but at line 8 it is let a: never.
Therefore tsc shows this error: Type 'never' has no call signatures at line 8.
But it doesn't if line 2 is let a: Foo | undefined; (removed the variable assignment)
I guess it will be something related with Type Inference. The docs states that:
In TypeScript, there are several places where type inference is used to provide type information when there is no explicit type annotation.
let x = 3; ^ let x: number
But I this example there is an explicit type annotation.
I understand that TS cannot know if the function c will be executed and, therefore, that a will be assigned. That is why I have put the explicit definition of the type of a in its declaration.
So why is the type defined for a not respected at line 8?