typescript

How to make class extend interface?


Given

interface Foo {
  x: number
  fn?(): void
}

class Bar implements Foo {
  x = 1
}

const bar = new Bar()
bar.fn

The last line errors: bar does not appear to be a Foo.


Solution

  • I solved it as I was asking it:

    You have to add interface Bar extends Foo {} like so:

    interface Foo {
      x: number
      fn?(): void
    }
    
    class Bar implements Foo {
      x = 1
    }
    
    interface Bar extends Foo {}
    
    const bar = new Bar()
    bar.fn // <-- works now