Kyle V.
Kyle V.

Reputation: 4792

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. 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

"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.

Upvotes: 1

Views: 1164

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

Remove declare from the namespace definition. 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,
    }
}

Upvotes: 1

Related Questions