gpt4 book ai didi

javascript - 有没有办法在 typescript 中实例化通用文字类型?

转载 作者:行者123 更新时间:2023-11-29 10:55:31 25 4
gpt4 key购买 nike

我想做一些可能非正统的事情(如果我们说实话,那几乎是无用的)所以我们开始吧:

我想传递一个文字作为通用参数,然后实例化它。考虑以下示例:

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

关于javascript - 有没有办法在 typescript 中实例化通用文字类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58337315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com