我想做一些可能非正统的事情(如果我们诚实的话,几乎没有用),所以我们开始:
我想传递一个文字作为通用参数,然后实例化它。考虑以下示例:
const log = console.log;
class Root<T = {}> {
// public y: T = {}; // this obviously doesn't work
// again this won't work because T is used a value. Even if it worked,
// we want to pass a literal
// public y: T = new T();
public x: T;
constructor(x: T) {
this.x = x;
}
}
class Child extends Root<{
name: "George",
surname: "Typescript",
age: 5
}> {
constructor() {
// Duplicate code. How can I avoid this?
super({
name: "George",
surname: "Typescript",
age: 5
});
}
foo() {
// autocomplete on x works because we gave the type as Generic parameter
log(`${this.x.name} ${this.x.surname} ${this.x.age}`);
}
}
const main = () => {
const m: Child = new Child();
m.foo();
};
main();
这可行,但我必须传递文字两次。一次用于自动完成工作的泛型,一次用于初始化的构造函数。啊。
另一种方法是在之外声明我的文字Child
。像这样:
const log = console.log;
class Root<T = {}> {
// public y: T = {}; // this obviously doesn't work
// again this won't work because T is used a value. Even if it worked,
// we want to pass a literal
// public y: T = new T();
public x: T;
constructor(x: T) {
this.x = x;
}
}
// works but ugh..... I don't like it. I don't want to declare things outside of my class
const literal = {
name: "George",
surname: "Typescript",
age: 5
}
class Child extends Root<typeof literal> {
constructor() {
super(literal);
}
foo() {
// autocomplete on x works because we gave the type as Generic parameter
log(`${this.x.name} ${this.x.surname} ${this.x.age}`);
}
}
const main = () => {
const m: Child = new Child();
m.foo();
};
main();
有没有什么神奇的方法可以实例化泛型类型,而无需通过构造函数再次显式提供它?