How can you instantiate a generic class in TypeScript? (1) When the value of the type parameter is known during compilation, (2) when the type to use as the parameter is passed as a string?
interface ITheValue {
TheValue: string;
}
class Foo implements ITheValue {
TheValue: string;
constructor(val: string) {
this.TheValue = val
}
}
class Bar implements ITheValue {
TheValue: string;
constructor(val: string) {
this.TheValue = val
}
}
class Buz<T implements ITheValue> {
Thing: T
constructor(val: string) {
this.T = new T(val);
}
getTheValue(): string {
return this.Thing.TheValue;
}
}
function run(whichOne: string, theValue: string): string {
var f: Foo = new Foo('foo value'); // This works.
// Can this be made to work? (Possible in languages like C#)
var buz = new Buz<whichOne>(theValue);
// Even this doesn't work.
var buz = new Buz<Foo>(theValue);
return `The value is: ${buz.getTheValue}.`;
}
document.querySelector("#app").innerHTML = run('Foo', 'the value');