最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can TypeScript classes remove access to inherited methods? - Stack Overflow

programmeradmin0浏览0评论

Classes can add methods when they extend from a super class, but can they do the opposite and remove methods? The goal is for these removed classes to not be accessible at pile time. I'm essentially trying to get (new car()). to not autoplete .drive() in an IDE.

class vehicle {
    drive() {
        ...
    }
}

class car extends vehicle {
    //previous attempt
    private drive() { // can't modify public/private

    }


}

Is there a way at pile time (tsc) to prevent car from having the method drive? Can we either delete it or modify it's accessibility?

Classes can add methods when they extend from a super class, but can they do the opposite and remove methods? The goal is for these removed classes to not be accessible at pile time. I'm essentially trying to get (new car()). to not autoplete .drive() in an IDE.

class vehicle {
    drive() {
        ...
    }
}

class car extends vehicle {
    //previous attempt
    private drive() { // can't modify public/private

    }


}

Is there a way at pile time (tsc) to prevent car from having the method drive? Can we either delete it or modify it's accessibility?

Share Improve this question edited Oct 4, 2016 at 0:16 David asked Oct 4, 2016 at 0:14 DavidDavid 2,4471 gold badge15 silver badges23 bronze badges 4
  • 3 that violates the SSP tenat. – Daniel A. White Commented Oct 4, 2016 at 0:15
  • 4 Inherited methods cannot be deleted or hidden. That would violate polymorphism. Could you explain what it is you're trying to acplish that makes you think it is necessary? – castletheperson Commented Oct 4, 2016 at 0:18
  • 5 This is a red-flag that your class hierarchy is broken. – juanpa.arrivillaga Commented Oct 4, 2016 at 0:23
  • What kinds of cars can't drive? – user663031 Commented Oct 4, 2016 at 3:25
Add a ment  | 

3 Answers 3

Reset to default 3

No. As noted in ments, this is indicative that your hierarchy is not correct. A derived class must always be substitutable for its base class.

You have to consider what happens when someone writes code like this

function doSomething(y: Vehicle) {
  y.drive();
}
let x = new Car();
doSomething(x);

One way to sinalize to people in the IDE would be to add a @deprecated ment in an overridden method's doc:

class MyClass {
  /**
   * @deprecated Please, don't use this because ...
   */
  override iDontWantPeopleUsingThis() {
    // Do nothing
  }
}

That would render the method with a strikethrough format in the IDE.

I know it wasn't meant for this, but perhaps you can't fix your hierarchy.

You can consider overriding the method which will always throw error. This way you can restrict that function at runtime but not pile time.

发布评论

评论列表(0)

  1. 暂无评论