typescript - 使用私有(private) typescript 时出现错误

标签 typescript protected

我正在写一些类型脚本类,这一点有问题

// BasePlugin.ts
export abstract class Base {
    protected abstract readonly commands: string[];
}


// Loader.ts

export const plugins: Base[] = [...] // A lot of plugins that extend Base that are already instantiated


// Help.ts
import { plugins } from './Loader'
export default class Help extends Base {
    commands = [
        '$help => sends this message'
    ];

    getAllHelp(): void {
        plugins.forEach(plugin => {
            plugin.commands.forEach(command => {
                ...
            )};
        )};
        ...
    }
}

我在plugin.command处遇到错误,并显示错误消息
[ts] Property 'commands' is protected and only accessible through an 
instance of class 'Help'.

我可能错了,但我想我已经在里面帮助访问这个。我在一个扩展Base的类中,为什么不能从其他commands访问Base数组?

最佳答案

在大多数具有protected概念的编程语言中,规则是Help只能访问在Help的实例上的受保护成员,因为这是与实现Help类相关的所有内容。如果Base的任何子类可以访问任何Base的实例的受保护成员,那么任何代码都可以通过定义Base的子类来访问任何实例的保护成员。

关于typescript - 使用私有(private) typescript 时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51715297/

相关文章:

c# - c# 中的 protected 与 protected 内部(再次)

java - 父类访问子类Java的 protected 成员

scala - 使用抽象父类(super class)实例和 "access to protected method not permitted"错误的 protected 方法

angular - 正确使用 Angular TypeScript 构造函数 - 无法解析所有参数

typescript - 如何使用 TypeScript 在 express 中输入 `request.query`?

html - 如何在 typescript 中使用/显示带有html标签的字符串

c++ - 错误 C2248 : cannot access protected member declared in class

javascript - 动态调用router函数

typescript - 如何使用 VSCode api 打开自定义编辑器

c++ - 删除 C++ 继承中虚拟类成员的代码重复