Craxal
Craxal

Reputation: 271

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

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:

Is this at all possible?

Upvotes: 3

Views: 1055

Answers (1)

Craxal
Craxal

Reputation: 271

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

type StringLiterals = (keyof StringLiterals)[keyof typeof StringLiterals];

export default StringLiterals;

Upvotes: 3

Related Questions