If we write this:
class A {}
function foo(): A {
return A; // No error. Why?
}
function foo2(): A {
return new A(); // Ok.
}
function bar(): typeof A {
return A; // Ok.
}
function bar2(): typeof A {
return new A(); // Error. It´s ok.
}
Type of A is not A, instead it is typeof A. So I don´t understand why first example works.
Thanks.
When asking Typescript to verify a return type A, you actually telling Typescript to make sure that the return value should structure as an instance of A.
When you return A, you are actually returning the prototype of A (typeof A)
So, in your case A is just an empty object with no fields so A
and new A()
have the same structure, so no error.
When you define a return type typeof A
TypeScript will compare the prototype of the function A (Class is actually a prototyped function after all) with A
this will also result in successful compilation.
But, when you compare the typeof A
(The prototype of A) with an instance of A
it is not the same. your compilation will return an error.
To sum it up:
Because of duck typing. A
has no members, so typeof A
is assignable to A
.
Contary is not the same: typeof A
has a constructor, so A
cannot be assigned to typeof A
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With