【问题标题】:Property 'propname' is a static member of type 'Class'属性“propname”是“类”类型的静态成员
【发布时间】:2020-02-20 23:05:46
【问题描述】:

此代码无法使用 typescript 编译。 它在第 11 行(最后一个)上显示 Property 'say' is a static member of type 'Animal

谁能解释一下原因?

class Animal {
    static say: string;
}
class Dog extends Animal{
    static say = 'bark'
}
class Cat extends Animal{
    static say = 'meow'
}
const animals:Animal[] = [Dog, Cat]
animals.filter(e=>e.say ==='meow')

【问题讨论】:

标签: typescript


【解决方案1】:

您已将animals 上的类型缩小为这些类的实例,而不是类本身。试试这个:

const animals: (typeof Animal)[] = [Dog, Cat];

或者干脆放弃类型,让它被推断出来;

【讨论】:

  • 是的,并且该注释不会导致错误,因为实例类型Animalempty,因此任何非空类型都可以分配给它,包括typeof Dog 和@ 987654326@。类应始终具有某种实例属性,以防止这种意外的结构兼容性。
猜你喜欢
  • 2019-08-11
  • 1970-01-01
  • 2018-05-31
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多