You cannot do this, since the actual type T will only be known at run time.
What can you do:
abstract class MyClass<T> { myvariable: T; constructor() { this.myvariable = this.getInitialValue(); } protected abstract getInitialValue(): T; }
Now you just extend this class, for example:
class MyStringClass extends MyClass<string> { protected getInitialValue(): string { return "init-value"; } }
Edit
What you are requesting cannot be done because T exists only in the typescript area and it does not "survive" during the compilation process.
For example, this:
class MyClass<T> { myvariable: T; constructor(value: T) { this.myvariable = value; } }
Compiles to:
var MyClass = (function () { function MyClass(value) { this.myvariable = value; } return MyClass; }());
As you can see, the compiled version does not have T , so you cannot use this information at run time to create a default value.
Another solution is to have a map of default values:
var defaultValues = { "string": "", "number": 0, "boolean": false } class MyClass<T> { myvariable: T; constructor(value: T) { this.myvariable = value; } } let a = new MyClass<string>(defaultValues.string); let b = new MyClass<boolean>(defaultValues.boolean);
You can also use static factory methods:
class MyClass<T> { myvariable: T; constructor(value: T) { this.myvariable = value; } static stringInstance(): MyClass<string> { return new MyClass<string>(""); } static numberInstance(): MyClass<number> { return new MyClass<number>(0); } static booleanInstance(): MyClass<boolean> { return new MyClass<boolean>(false); } } let a = MyClass.stringInstance(); let b = MyClass.booleanInstance();
source share