Home > Blockchain >  extended base interface applied to a class
extended base interface applied to a class

Time:12-25

I am having trouble assigning an extended interface to a class.

I add a minimal example below (and playground at the end of the post):

interface A {
    hello:string
}

interface Extension extends A {
    bye:string
}

class Greeting implements Extension {
    constructor(){
        this.hello="hi"
        this.bye= "bye"
    }
}

The error is: Property 'hello' does not exist on type 'Greeting'. Between other errors.

I understand this is because there is no type definition, but why would it be if I am implementing this interface already? Is there any better way to do this without basically repeating the definition of Extension interface ?

To me the way it is written makes sense, but I just can't really get how this should be properly done. Can you help me?

TSPlayground

CodePudding user response:

The following code should solve the issue:

...
class Greeting implements Extension {
    // initialize the class property
    public hello;
    public bye;
    constructor(){
        this.hello="hi"
        this.bye= "bye"
    }
}

CodePudding user response:

Use class'es instead of interface's, because the latter are just type, they do not do anything at runtime:

class A {
    hello: string
}

class B extends A {
    bye: string
}

class Greeting extends B {
    constructor() {
        super()
        this.hello = "hi"
        this.bye = "bye"
    }
}

Playground Link

  • Related