Just as static methods cannot access instance members, a static method cannot use an instance type argument.
For this reason, your static method must be generic and accept a type argument. I highlight this using U in a static function and T in a class. It is important to remember that the type of instance T does not match the type of static method U
class Foo<T> { public static factory<U>(item: U): Foo<U> { return new Foo<U>(); } instanceMethod(input: T) : T { return input; } }
Then you call it by passing the type argument immediately before the bracket, for example:
var f: Foo<number> = Foo.factory<number>(1);
When type inference is possible, type annotation may be omitted:
var f: Foo<number> = Foo.factory(1);
The variable f is an instance of Foo with an argument of type number , so the instanceMethod method takes a value of type number (or any ).
f.instanceMethod(123); // OK f.instanceMethod('123'); // Compile error
Fenton
source share