作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试为我的类使用通用接口(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/
我是一名优秀的程序员,十分优秀!