2

In Typescript 2.5.2 following does not work:

interface I {
    m?():void;
}

class C implements I {
}

let c = new C();
c.m();  <== Error : TS2339:Property 'm' does not exist on type 'C'.

Why is the m method not found?

If I add:

interface C extends I {}

It's ok! Or if I add:

let c = new C() as C & I;

It's ok too.

As I understand implements should combine C and I types as C & I. Is it an issue?

1
  • Interfaces are implemented abstract classes are extended. Interfaces are just a contract saying that any methods are going to be supported in the actual class. You need to implement m in class C Commented Sep 28, 2017 at 18:47

1 Answer 1

2

The interface you have is a weak type that doesn't enforce the property m on implementers.

TypeScript is smart enough to see that m is definitely not on your class, but you can prevent the error by asking TypeScript to treat the variable as the interface:

let c: I = new C();
c.m();

Despite this trick, you'll still have a runtime problem, which TypeScript tried to warn you about.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.