Can I default export constants and type alias from the same module?

Viewed 798

I have a project with numerous objects containing constant string values in them.

const StringLiterals = {
    a: "LetterA",
    b: "LetterB",
    c: "LetterC"
};

export default StringLiterals;

In many cases, these string constants are used as parameters. I want ensure only strings from these constants are being used, so I define a type alias.

type StringLiteral = keyof typeof StringLiterals;

Right now, I have to redefine this type alias everywhere I want to use it. I'd define the string values and the type alias in the same module such that I can do something like this:

import StringLiteral from "./StringLiteral";

function doSomething(str: StringLiteral) {
    if (str === StringLiteral.a) { ... }
}

Also:

  • I don't want two different modules, one containing the type and the other containing the string values.
  • I don't want enums, because they don't let you map identifiers to string values; they have to be numeric. I also want to avoid a lot of array referencing to translate between string and numeric values.

Is this at all possible?

1 Answers
Related