typescript 应用于类的扩展基接口

k4ymrczo  于 2022-12-27  发布在  TypeScript
关注(0)|答案(2)|浏览(107)

我在为类分配扩展接口时遇到了问题。
我添加一个最小的例子如下(和操场在帖子的结尾):

interface A {
    hello:string
}

interface Extension extends A {
    bye:string
}

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

错误为:Property 'hello' does not exist on type 'Greeting'.在其他错误之间。
我知道这是因为没有类型定义,但是如果我已经实现了这个接口,为什么会这样呢?有没有更好的方法来实现这个接口,而基本上不重复Extension接口的定义?
对我来说,它的写作方式是有意义的,但我真的不知道该如何正确地完成它。你能帮助我吗?

TSP铺设地面

wwtsj6pe

wwtsj6pe1#

下面的代码应该可以解决这个问题:

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

1yjd4xko2#

使用class 'es代替interface's,因为后者只是类型,它们在运行时不做任何事情:

class A {
    hello: string
}

class B extends A {
    bye: string
}

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

Playground链接

相关问题