javascript - 有没有办法在打字稿中实例化通用文字类型?
问题描述
我想做一些可能是非正统的(如果我们诚实的话,几乎是无用的)所以我们开始吧:
我想将文字作为通用参数传递,然后实例化它。考虑以下示例:
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();
是否有任何神奇的方法来实例化 Generic 类型而不通过构造函数再次显式提供它?
解决方案
您可以使用一个中间包装器来处理扩展泛型和调用构造函数:
function fromRoot<T>(x: T) {
return class extends Root<T> {
constructor() {
super(x)
}
}
}
接着:
class Child extends fromRoot({
name: "George",
surname: "Typescript",
age: 5
}) { etc }
推荐阅读
- javascript - 将 IF/Else 条件转换为 Ramda Cond 失败
- python - 为什么我收到 IndexError: list index out of range 消息?
- bash - 在 bash 脚本中运行多个命令
- ios - Xcode 的 SceneKit 编辑器渲染 .dae 文件错误,Xcode 有时在预览期间崩溃
- autodesk-forge - 单击“完成”按钮后如何进行测量?
- php - 使用 googlepagespeed api 的屏幕截图
- python - 根据没有公共列的坐标合并数据框
- php - 使用按钮问题从表中删除 1 行
- unit-testing - Vue.js vuetify test-utils 测试:单元失败
- coldfusion - Coldfusion 11 应用程序服务器在 Windows 10 中自动停止