如果你不使用
typeof Box
BoxType<T>
作为接受
T
返回一个
Box<T>
abstract class Box<T> {
constructor(public initialValue: T) {}
public abstract getDefaultThing(): T;
}
type BoxType<T> = new (initialValue: T) => Box<T>;
interface Config<T> {
boxType: BoxType<T>;
initialValue: any;
}
function loadConfig<T>(config: Config<T>) {
return new config.boxType(config.initialValue); // no cast
}
class MyBox extends Box<string> {
public getDefaultThing(): string { // there was a typo here this was any
return `${this.initialValue} world`;
}
}
const config = { // no explcit type needed
boxType: MyBox,
initialValue: "hello",
};
const loaded = loadConfig(config); // loaded is Box<string>
console.log(loaded.getDefaultThing()); // prints "hello world"
loadConfig
返回派生类型而不仅仅是抽象类型(即
MyBox
不
Box<string>
abstract class Box<T> {
constructor(public initialValue: T) {}
public abstract getDefaultThing(): T;
}
type BoxType<T, TBox extends Box<T>> = new (initialValue: T) => TBox;
interface Config<T, TBox extends Box<T>> {
boxType: BoxType<T, TBox>;
initialValue: any;
}
function loadConfig<T, TBox extends Box<T>>(config: Config<T, TBox>) {
return new config.boxType(config.initialValue); // no cast
}
class MyBox extends Box<string> {
public getDefaultThing(): string { // there was a typo here this was any
return `${this.initialValue} world`;
}
}
const config = { // no explcit type needed
boxType: MyBox,
initialValue: "hello",
};
const loaded = loadConfig(config); // loaded is MyBox
console.log(loaded.getDefaultThing()); // prints "hello world"