简体   繁体   English

TypeScript中的嵌套类抛出错误

[英]Nested class in TypeScript throwing error

I was following instructions in the official TypeScript handbook under the section "Merging Namespaces with Classes" for how to get nested classes. 我正在遵循官方TypeScript手册中“使用类合并命名空间”部分下的说明来获取嵌套类。 But it looks like if I try to add a function declaration of any type in the child class definition I get the TS error 但是看起来如果我尝试在子类定义中添加任何类型的函数声明,都会收到TS错误

"An accessor cannot be declared in an ambient context" “无法在环境上下文中声明访问器”

I don't know what this means or why I'm getting this when I'm following the example exactly as far as I can tell. 我不知道这是什么意思,也不知道为什么我完全按照示例讲解时为什么得到这个。

export class Schedule {
    // ...
}

export declare namespace Schedule {
    export class MaxGracePeriod {
        // Static, read-only constants in TypeScript (See: https://stackoverflow.com/a/22993349/1504964)
        public static get Hourly(): number { return 12; }
        public static get Daily(): number { return 12; }
        public static get Weekly(): number { return 12; }
        public static get Monthly(): number { return 24; }
        public static get Yearly(): number { return 24; }       
        //                ~~~~~~ => "An accessor cannot be declared in an ambient context"
    }

    export enum DaysOfWeek {
        Sunday = 0,
        Monday = 1,
        Tuesday = 2,
        Wednesday = 3,
        Thursday = 4,
        Friday = 5,
        Saturday = 6,
    }
}

I get the red squiggle and error on the Hourly() , Daily() , etc. definitions. 我在Hourly()Daily()等定义上出现红色花键和错误。

Remove declare from the namespace definition. 从名称空间定义中删除declare You don't need that. 不用了

export class Schedule {
    // ...
}

export namespace Schedule {
    export class MaxGracePeriod {
        public static get Hourly(): number { return 12; }
        public static get Daily(): number { return 12; }
        public static get Weekly(): number { return 12; }
        public static get Monthly(): number { return 24; }
        public static get Yearly(): number { return 24; }       
    }

    export enum DaysOfWeek {
        Sunday = 0,
        Monday = 1,
        Tuesday = 2,
        Wednesday = 3,
        Thursday = 4,
        Friday = 5,
        Saturday = 6,
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM