What does it mean when a class implements itself i

2020-04-30 01:37发布

I'm trying to add dependency injection to a plain Typescript project, found an npm package called inversify. So looking at the examples I came across this code:

import { Container, injectable, inject } from "inversify";

@injectable()
class Katana {
    public hit() {
        return "cut!";
    }
}

@injectable()
class Shuriken {
    public throw() {
        return "hit!";
    }
}

@injectable()
class Ninja implements Ninja {

    private _katana: Katana;
    private _shuriken: Shuriken;

    public constructor(katana: Katana, shuriken: Shuriken) {
        this._katana = katana;
        this._shuriken = shuriken;
    }

    public fight() { return this._katana.hit(); };
    public sneak() { return this._shuriken.throw(); };

}

var container = new Container();
container.bind<Ninja>(Ninja).to(Ninja);
container.bind<Katana>(Katana).to(Katana);
container.bind<Shuriken>(Shuriken).to(Shuriken);

What does it mean for class Ninja to implement the class Ninja?

class Ninja implements Ninja {

On the example the container is binding the class to itself, is it related to that?

var container = new Container();
container.bind<Ninja>(Ninja).to(Ninja);

1条回答
兄弟一词,经得起流年.
2楼-- · 2020-04-30 02:33

I don't think this has any meaning or adds any type safety. It's just a quirk of how the compiler performs type checking. The implements are checked after the class is already fully typed. So the compiler can check an implements clause that involves the class itself.

In this case it's not particularly useful to use the class in the implements clause (as you are basically saying the class should implement itself which it always does). We can use this feature to do useful things, for example we can ensure the class members are of a specific type

class Test implements Record<keyof Test, () => void> {
  test() { } 
}

class Test2 implements Record<keyof Test2, () => void>{
    test(a: number) { }  // error
}
查看更多
登录 后发表回答