Accessing global enums in vue

Viewed 133

How can I consume global enums in vue, or another way to declare them?

I have the following setup:

In my types/auth.d.ts:

export {};

declare global {
  enum MyEnum {
    some = "some",
    body = "body",
    once = "once",
    told = "told",
    me = "me"
  }
}

I can't seem to use the declared enum in my code. In script in sfc files and normal .ts files, it does get IntelliSensed, but causes an error on runtime:

auth.ts:54 Uncaught ReferenceError: AuthType is not defined

In template, it doesn't get recognised at all. For example, if I use it in a v-if such as follows:

<tr v-if="myObject.mytype === MyEnum.some">

where

type MyObject = {
  ...
  mytype: MyEnum
}

it throws me the following error:

Property 'AuthType' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $props: Partial<{}> & Omit<Readonly<ExtractPropTypes<{}>> & VNodeProps & AllowedComponentProps & ComponentCustomProps, never>; ...

I am using Vue 3 with vite, if it makes any difference.

1 Answers

typescript enums provide type safety while writing to code but don't pass throught compilation. You still have keep in mind javascript. Closest alternative is Object.freeze and you need to modify other parts of your code to fit to your use case.

const myEnum = Object.freeze({
    some : "some",
    body : "body",
    once : "once",
    told : "told",
    me : "me"
})
Related