Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return class type in TypeScript

Tags:

typescript

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.

like image 548
José Carlos Lama Avatar asked Aug 24 '15 21:08

José Carlos Lama


2 Answers

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:

  • The prototype of A which is {}, has all the fields of A which is {} -> pass
  • An instance of A is {} and it also contains all the fields of A which is {} -> pass
  • The prototype of A which is a constructor function with no static fields, but fulfill the required {}, is the same as A which is {} -> pass
  • An instance of A which is {} is not the same as the prototype of A which has an extra constructor function -> fail
like image 159
gilamran Avatar answered Oct 02 '22 13:10

gilamran


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.

like image 20
Artem Avatar answered Oct 02 '22 12:10

Artem