sys
sys

Reputation: 25

Typescript: class implements interface issue?

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?

Upvotes: 2

Views: 558

Answers (1)

Fenton
Fenton

Reputation: 250822

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.

Upvotes: 2

Related Questions