【问题标题】:What is the equivalent of protected in TypeScript?TypeScript 中的 protected 等价物是什么?
【发布时间】:2013-03-07 15:55:29
【问题描述】:

TypeScript中的protected是什么?

我需要在基类中添加一些成员变量,以便仅在派生类中使用。

【问题讨论】:

标签: typescript


【解决方案1】:

更新

2014 年 11 月 12 日。TypeScript 1.3 版可用并包含受保护的关键字。

2014 年 9 月 26 日。protected 关键字已登陆。它目前处于预发布状态。如果您使用的是非常新版本的 TypeScript,您现在可以使用 protected 关键字……下面的答案适用于旧版本的 TypeScript。享受吧。

View the release notes for the protected keyword

class A {
    protected x: string = 'a';
}

class B extends A {
    method() {
        return this.x;
    }
}

旧答案

TypeScript 只有 private - 不受保护,这仅意味着在编译时检查期间是私有的。

如果你想访问super.property,它必须是公开的。

class A {
    // Setting this to private will cause class B to have a compile error
    public x: string = 'a';
}

class B extends A {
    method() {
        return super.x;
    }
}

【讨论】:

    【解决方案2】:

    下面的方法怎么样:

    interface MyType {
        doit(): number;
    }
    
    class A implements MyType {
        public num: number;
    
        doit() {
            return this.num; 
        }
    }
    
    class B extends A {
        constructor(private times: number) {
            super();
        }
    
        doit() {
            return super.num * this.times; 
        }
    }
    

    由于num 变量被定义为公共,这将起作用:

    var b = new B(4);
    b.num;
    

    但由于接口中没有定义,所以:

    var b: MyType = new B(4);
    b.num;
    

    将导致The property 'num' does not exist on value of type 'MyType'
    你可以在这个playground试试。

    您也可以将其包装在模块中,同时仅导出接口,然后从其他导出的方法中返回实例(工厂),这样变量的公共范围将“包含”在模块中。

    module MyModule {
        export interface MyType {
            doit(): number;
        }
    
        class A implements MyType {
            public num: number;
    
            doit() {
                return this.num; 
            }
        }
    
        class B extends A {
            constructor(private times: number) {
                super();
            }
    
            doit() {
                return super.num * this.times; 
            }
        }
    
        export function factory(value?: number): MyType {
            return value != null ? new B(value) : new A();
        }
    }
    
    var b: MyModule.MyType = MyModule.factory(4);
    b.num; /// The property 'num' does not exist on value of type 'MyType'
    

    修改版在此playground

    我知道这不完全符合您的要求,但非常接近。

    【讨论】:

      【解决方案3】:

      至少目前(0.9 版)规范中没有提到受保护

      http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-29
        • 2010-11-23
        • 2020-08-16
        • 2014-05-08
        • 2014-11-29
        • 2014-06-12
        • 1970-01-01
        相关资源
        最近更新 更多