首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何修复“类型为...的参数不可赋值给类型为...的参数”错误?

如何修复“类型为...的参数不可赋值给类型为...的参数”错误?
EN

Stack Overflow用户
提问于 2019-04-28 01:17:42
回答 1查看 1.4K关注 0票数 2

给定的

代码语言:javascript
复制
abstract class A {
  constructor() {
    this.initialize()
  }

  initialize<T extends {
    [t in keyof this]?: boolean
  }>(todos?: T) {
    // Do something
  }
}

class B extends A {
  initialize() {
    super.initialize({ // <-- it will throw error starting on this open bracket
        test: false
    })
  }

  test() {
    return 'test'
  }
}

为什么上面的代码抛出错误,声明{ test: false }不能赋值给{[t in keyof this]?: boolean}?虽然很明显是这样。

‘'test’是B的关键字之一,对吧?keyof this会引用B的密钥,对吗?

EN

回答 1

Stack Overflow用户

发布于 2019-04-28 10:09:57

@JGoodgive那么我如何才能真正引用当前类呢?因为我需要它来指向当前类,以便以后在类的后代中使用。我可以通过以下方式来实现:

代码语言:javascript
复制
abstract class A<Model> {
  constructor() {
    this.initialize()
  }

  initialize<T extends {
    [t in keyof Model]?: boolean
  }>(todos?: T) {
    // Do something
  }
}

class B extends A<B> {
  initialize() {
    super.initialize({
      test: true,
      initialize: false,
    })
  }

  test() {
    return 'test'
  }
}

但是把B传给B似乎很愚蠢,你不这样认为吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55883031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档