【发布时间】:2023-01-22 11:06:55
【问题描述】:
在 TypeScript 中,如何创建泛型类的实例? (1) 当类型参数值在编译时已知,并且 (2) 何时将用作类型参数的类型名称作为字符串值传递?
https://jsfiddle.net/zn71am4v/
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'); // Well at least this works.
// Can this be made to work? (It can in a proper language like C# :p)
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');
【问题讨论】:
标签: typescript typescript-generics