1

I'm trying to create a collection of enums to be used inside an index.ts file. Rather than keeping these enums directly inside the index.ts file, I want to import them from another file.

To do this, I tried declaring a namespace inside a declaration file:

declare namespace reservedWords {
  enum Variables {
    const = 'const',
    let = 'let',
    var = 'var',
  }
  ...
  // more enums and other things
}

export default reservedWords;

I then try to import this in the index.ts file:

import reservedWords from 'reservedWords.d.ts';

...

if (thing === reservedWords.Variables.const) doSomething();

Before compiling, I tried to add my src directory to my typeroots since that's where I'm keeping the reservedWords.d.ts file:

    "typeRoots" : ["./src", "./node_modules/@types"],

When I compile the index.ts file with tsc, I'm seeing that the compiled index.js file is saying that it's importing reservedWords, but nothing with that name exists in the bin (export) folder.

import reservedWords from 'reservedWords';

How can I get the index.ts file to use these enums? Not sure how necessary using a namespace is, but I figured organizing these enums inside a namespace in a declaration file would be the best thing to do.

2 Answers 2

1

You would need to export the enums

declare namespace reservedWords {
  export enum Variables {
    const = 'const',
    let = 'let',
    var = 'var',
  }
  ...
  // more enums and other things
}

export default reservedWords;

And under index.ts

    import * as reservedWords from 'reservedWords'
Sign up to request clarification or add additional context in comments.

2 Comments

How would Variables be used from index.ts like this?
reservedWords.Variables.const
1

You may be looking for the constant enums. This typescript feature will help you to generate enum values in requested places. Here's an example for your case:

const enum Variables {
  const = 'const',
  let = 'let',
  var = 'var',
}

More details could be found in the official documentation.

P.S.: I suppose there's no need to use import reservedWords from 'reservedWords.d.ts'; as you already specified type type roots.

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.