当一个类在Typescript中实现自己时,这是什么意思 [英] What does it mean when a class implements itself in Typescript

查看:59
本文介绍了当一个类在Typescript中实现自己时,这是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将依赖项注入添加到一个普通的Typescript项目中,发现了一个名为inversify的npm包.因此,看一下这些代码中的示例:

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);

推荐答案

我认为这没有任何意义,也没有增加任何类型安全性.这只是编译器如何执行类型检查的一个怪癖.在类已完全键入后检查工具.因此,编译器可以检查涉及类本身的 implements 子句.

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.

在这种情况下,在 implements 子句中使用该类并不是特别有用(因为您基本上是在说该类应该实现其自身始终执行的功能).我们可以使用此功能来做有用的事情,例如,可以确保类成员是特定类型

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
}

这篇关于当一个类在Typescript中实现自己时,这是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆