Is there any way to instantiate a Generic literal type in typescript?(有没有办法在TypeScrip中实例化泛型文字类型?)
本文介绍了有没有办法在TypeScrip中实例化泛型文字类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做一些可能非正统的事情(如果我们诚实的话,也几乎毫无用处),所以我们开始吧:
我希望将文本作为泛型参数传递,然后实例化它。请考虑以下示例:
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();
是否有什么神奇的方法可以实例化泛型类型,而无需通过构造函数再次显式提供它?
推荐答案
您可以使用中间包装器,该包装器同时负责扩展泛型和调用构造函数:
function fromRoot<T>(x: T) {
return class extends Root<T> {
constructor() {
super(x)
}
}
}
然后:
class Child extends fromRoot({
name: "George",
surname: "Typescript",
age: 5
}) { etc }
PG
这篇关于有没有办法在TypeScrip中实例化泛型文字类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:有没有办法在TypeScrip中实例化泛型文字类型?
猜你喜欢
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01