Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

javascript - What does it mean when a class implements itself in Typescript

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...