1
abstract class AbstractCard {
  foo = 1
  getKeys(): Array<keyof this> {
    return ['foo']
  }
}

class Card extends AbstractCard {
  bar = 2
  getKeys(): Array<keyof this> {
    return [...super.getKeys(), 'bar']
  }
}

const logCard = (card: AbstractCard) => {
  console.log(card.getKeys())
}

const card = new Card()

logCard(card)


TS2345:'Card' 类型的参数不可分配给'AbstractCard' 类型的参数。'getKeys()' 返回的类型在这些类型之间不兼容。类型“(keyof Card)[]”不可分配给类型“(keyof AbstractCard)[]”。类型“keyof Card”不可分配给类型“keyof AbstractCard”。类型“bar”不能分配给类型“keyof AbstractCard”。

通过使用泛型解决

abstract class AbstractCard {
  foo = 1
  getKeys(): Array<keyof this> {
    return ['foo']
  }
}

class Card extends AbstractCard {
  bar = 2
  getKeys(): Array<keyof this> {
    return [...super.getKeys(), 'bar']
  }
}

const logCard = <T extends AbstractCard>(card: T) => {
  console.log(card.getKeys())
}

const card = new Card()

logCard(card)
4

0 回答 0