使用私人打字稿时出现错误

时间:2018-08-06 20:37:51

标签: 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数组?

1 个答案:

答案 0 :(得分:0)

就像大多数具有protected概念的编程语言一样,规则是Help只能访问Help实例上的受保护成员,因为那应该是所有相关的实现Help类。如果Base的任何子类可以访问Base的任何实例的受保护成员,那么任何代码都可以通过定义Base的子类来访问Base的任何实例的受保护成员。 ,这与仅公开成员太相似了。