【问题标题】:Typescript - accept keyof child class on function in base classTypescript - 在基类中的函数上接受 keyof 子类
【发布时间】:2020-07-17 04:08:47
【问题描述】:

我的基类上有一个函数,它采用要观察的属性的名称:

class Parent {
    listenTo(prop: keyof this);
}

然后我有一个子类,我想查看它自己的属性之一

class Child extends Parent {
    foo = 3;
    constructor() {
        this.listenTo('foo');
    }
}

但这不起作用。它抱怨“foo”不是有效键之一,然后只列出来自父级的键,而不是子级。是否有任何方法可以让 Parent 中的函数声明查看实际类型,而不仅仅是其本身?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    现在在操场上测试它似乎可以工作,但你需要一个super 电话:

    class Parent {
        listenTo(prop: keyof this) {}
    }
    
    class Child extends Parent {
        foo = 3;
        constructor() {
            super();
            this.listenTo('foo'); // ok
            this.listenTo('foo2'); // error
        }
    }
    

    TypeScript Playground

    确保打字稿版本已更新

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2021-10-06
      • 2018-12-12
      • 2021-02-22
      • 1970-01-01
      相关资源
      最近更新 更多