【问题标题】:Why implementing a class with non public members is prohibited in TypeScript?为什么在 TypeScript 中禁止实现具有非公共成员的类?
【发布时间】:2016-02-05 00:26:13
【问题描述】:

具有以下类:

class Trait {
    publicMethod() {
        this.privateMethod();
        // do something more
    }

    private privateMethod() {
        // do something usefull
    }
}

如果我尝试通过以下方式实现它:

class MyClass implements Trait {
    publicMethod() {}
}

我收到以下错误:

MyClass 错误地实现了接口 Trait。财产 “MyClass”类型中缺少“privateMethod”

如果我尝试通过以下方式实现它:

class MyClass implements Trait {
    publicMethod() {}

    private privateMethod() {}
}

我收到以下错误:

MyClass 错误地实现了接口 Trait。类型有单独的 私有属性“privateMethod”的声明

如果我尝试以下操作:

class MyClass implements Trait {
    publicMethod() {}

    public privateMethod() {}
}

我收到错误:

MyClass 错误地实现了接口 Trait。财产 “privateMethod”在“Trait”类型中是私有的,但在“MyClass”类型中不是私有的

受保护的方法以及私有和受保护的属性也会发生同样的事情。因此,似乎要能够实现类,该类的所有成员都必须是公共的。

为什么在 TypeScript 中禁止实现具有非公共成员的类?

编辑: 好的,实现将类视为接口,并且因为接口不能具有私有成员,所以您不能实现具有非公共成员的类。但是为什么不忽略非公共成员呢?

提出这个问题是因为我想应用 mixins 来重用代码。另一种方法是组合,但是有一个使用 mixins 和非公共成员的解决方案。

解决办法如下:

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        })
    });
}

interface ITrait {
    publicMethod();
}

class Trait implements ITrait {
    publicMethod() {
        this.privateMethod();
        // do something more
    }

    private privateMethod() {
        // do something usefull
    }
}

class MyClass implements ITrait {
    publicMethod() {}
}

applyMixins(MyClass, [Trait]);

【问题讨论】:

  • 一个类 extends 另一个类和 implements 一个接口。 Trait 是一个类,而不是一个接口
  • @BrunoGrieder 实际上,implements 用于 TypeScript 中的 mixins (typescriptlang.org/Handbook#mixins-mixin-sample)
  • @MartinVseticka 好的。我的不好,我刚刚学到了一些东西。谢谢

标签: typescript


【解决方案1】:

本质上,关键字implementsTrait 类视为接口,接口不能有私有方法。

在此处查看 mixins 背后的基本原理和此处的私有方法:https://github.com/Microsoft/TypeScript/issues/5070

编辑:很容易发现 mixins 中私有方法的第一个问题以及它们不受支持的原因。如果两个特征有同名的私有方法怎么办?当务之急是它们不能相互影响,但这不容易做到(考虑instance['my' + 'method']() 符号)。

来自TypeScript documentation on CodePlex

在上面你可能会注意到的第一件事是,而不是使用 “扩展”,我们使用“实现”。这将类视为接口, 并且只使用 Disposable 和 Activatable 后面的类型,而不是 实施。这意味着我们必须提供 在课堂上实施。除了,这正是我们想要避免的 通过使用 mixins。

【讨论】:

  • 感谢您的回复。我不同意,但至少是有原因的。
  • 你不同意我的观点吗?还是配合 mixins 的实现?
  • 我不同意“关键字 implements 将 Trait 类视为接口,接口不能有私有方法。”这句话。我认为这是不够的理由。为什么不直接忽略非公共成员?
  • 公共成员也可能发生名称冲突,并且行为同样奇怪,最后应用的mixin获胜。
  • 我只能添加 TypeScript 的主要贡献者对问题所说的内容:github.com/Microsoft/TypeScript/issues/…
猜你喜欢
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 2017-08-22
  • 2013-04-22
  • 2013-02-03
  • 2010-10-22
相关资源
最近更新 更多