1

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.

6
  • Hint: if you never use the constructor of your class, and it does not have any methods besides static ones, you should not be using class syntax at all. Commented Feb 5, 2018 at 17:17
  • @Bergi what should I use instead? interface? Commented Feb 5, 2018 at 17:49
  • A simple object literal. For typing? Yes, probably an interface. Commented Feb 5, 2018 at 18:42
  • @Bergi Hmm it gives me a bunch of errors with my method declarations if I change it to interface... Commented Feb 5, 2018 at 18:53
  • @Bergi How would I declare it as a simple object literal? Commented Feb 5, 2018 at 19:23

1 Answer 1

1

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,
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.