When working with TypeScript, it may seem strange at first why the language throws errors based on the signature of your static function. Here's a breakdown:
If you use a class name (e.g., TestCls
) to specify the return type of a function, TypeScript expects the function to return an instance of that class, not the constructor itself. So when you write something like foo(): MyClass
, TypeScript anticipates foo()
to return a new instance of MyClass
.
Additionally, by defining a function signature in this way, TypeScript will enforce that the specified return type is accurate. This means that using
: MyClass</code is essentially a form of <em>type assertion</em>, overriding TypeScript's inferred return type.</p>
<p>The situation gets odd when considering a scenario like this:</p>
<pre><code>function hello (): string {
return 5;
}
TypeScript will flag an error stating
Type '5' is not assignable to type 'string'
. It appears that TypeScript struggles to differentiate between a class and its instance as they are both considered
object
s in the end.
In summary; Remove the return type assertion from your static function to avoid issues. TypeScript is capable of inferring the return type without explicit declaration.
export class TestCls {
static SomeStaticFn() {
// Do some stuff...
// Return the class descriptor to enable "fluid usage" of SomeStaticFn
return TestCls;
}
}
TestCls.SomeStaticFn().SomeStaticFn();