1

I want to declare an enum in typescript

// types/types.d.ts
declare enum SectionType {
    H1 = "H1",
    H2 = "H2",
    H3 = "H3",
    H4 = "H4",
    H5 = "H5",
    H6 = "H6",
    P = "P",
}

declare type Section = {
    type: SectionType
    text: string
}

declare type Page = {
    slug: string
    sections: Section[]
}

declare type Site = {
    slug: string
    pages: Page[]
}

but at runtime, when running this:

const defaultHomePage = {
    slug: 'home',
    sections: [
        {
            type: SectionType.H1,
            text: 'Hello World'
        }
    ]
}

I get an error:

Uncaught ReferenceError: SectionType is not defined

What's going wrong here?

5
  • How did you compile the scripts? Did you export an import the enum? Commented Jun 1, 2021 at 21:51
  • I'm sorry, it was in a declaration file (.d.ts) instead of a normal ts file. AFAIK I dont need to export types from a declaration file but I may be misunderstanding things Commented Jun 1, 2021 at 21:52
  • Ah. Yeah, don't do that Commented Jun 1, 2021 at 21:56
  • Is there then no way to globally declare enums in Typescript? Commented Jun 1, 2021 at 21:57
  • 1
    Sure there is, but to use them at runtime you can't have them only in a declaration file. See the duplicates for various solutions and workarounds. Commented Jun 1, 2021 at 22:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.