gpt4 book ai didi

generics - TypeScript 泛型类 : Cannot assign to Generic Type Variable

转载 作者:行者123 更新时间:2023-12-02 10:49:47 25 4
gpt4 key购买 nike

我正在尝试为我的类使用通用接口(interface)。
我的类有一个泛型类型,它扩展了一个接口(interface)和一个具有该类型的类变量。但是,一旦我尝试为该变量赋值,编译器就会给我一个错误。(示例:A 类)

当我不扩展通用类型时,它可以工作。 (例如:B 类)

//Generic Classes problem
interface MyStateInterface {
test?: number
}

class A<IState extends MyStateInterface> {
protected state: IState;

constructor() {
// Error here
this.state = {
test: 1
};
}
}

class B<IState extends MyStateInterface> {
protected state: MyStateInterface;

constructor() {
this.state = {
test: 1
};
}
}

有没有人可以解决这个问题?

最佳答案

class A<IState extends MyStateInterface> {
protected state: IState;

constructor() {
this.state = { ...

你说的是 IState扩展 MyStateInterface .这意味着有人可以实例化 A具有比 MyStateInterface 更具体的类型.具体来说,有人可以添加新的必需属性:
interface MyCoolState extends MyStateInterface {
required: string;
}
let x = new A<MyCoolState>();

发生这种情况时,您的构造函数代码会违反 MyCoolState 的约定。通过初始化 state具有缺少 required 的值.

你如何解决这个问题取决于你想要做什么。通常当人们发现自己处于这种情况时,正确的做法是根本不要泛型——子类覆盖 state 已经是合法的了。具有更多派生的类型,因此如果这是您要启用的行为,则根本不需要泛型。

关于generics - TypeScript 泛型类 : Cannot assign to Generic Type Variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41045079/

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