2
declare namespace Space.NewSpace {
    enum TestEnum {
        Foo,
        Bar
    }
}

in my .tsx file I'm trying to use the enum as follows:

Space.NewSpace.TestEnum.Foo

But it's throwing this error: Uncaught TypeError: Cannot read property 'Space' of undefined

2
  • 1
    Try getting rid of declare? Unless you're importing the namespace from somewhere else? Commented Sep 6, 2019 at 3:54
  • If I remove it, it says Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier. Commented Sep 6, 2019 at 5:50

1 Answer 1

3

Your TypeError is a JavaScript runtime error and not (directly) related to TS type system.

When you use declare namespace, you expect a third party library script to provide the namespace/property on the global namespace for you at runtime. declare xxx keyword is only relevant for compile type, e.g. to make global variables known for TS compiler. If there is no global property provided later on, you get above error.

So, if you have a third party namespace you depend on, you'll want to write:

declare namespace Space.NewSpace {
  enum TestEnum {
    Foo,
    Bar
  }
}

... and the library would provide the namespace similar to this:

var Space = {
  NewSpace: {
    // enum simplified here
    TestEnum: {"0": "Foo", "1": "Bar", Foo: 0, Bar: 1}
  }
};

If you write a namespace for your own code, leave out the declare keyword and export the members.

namespace Space.NewSpace {
  export enum TestEnum {
    Foo,
    Bar
  }
}

console.log(Space.NewSpace.TestEnum[0]); // Foo
Sign up to request clarification or add additional context in comments.

4 Comments

removing declare throws this error: Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier.
@ZeroDarkThirty ...because you have to use declare, when you want to define an ambient (without implementation) namespace in a .d.ts file. Does this sample repo help?
ah so you're saying if i have a namespace with implementation (like my original post), it can't have the declare keyword? in that case do i need the actual implementation in another namespace (minus declare keyword)?
yes. and in this case, just write the implementation (namespace xxx) and drop the declaration (declare namespace xxx) entirely.

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.