10

I've added a global property in main.ts, and am trying to access this in a component. however I'm getting the error:

Property '$const' does not exist on type 'ComponentPublicInstance<{}, {}, {}, {}, {}, EmitsOptions, {}, {}, false, ComponentOptionsBase<{}, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, string, {}>>'.Vetur(2339)

I think I need to augment the type, typescript considers $const to be any type right now, however I don't know how to do this in Vue 3 and there is no mention in the docs.

main.ts

import { createApp } from "vue";
import App from "./App.vue";
import store from "./store";
import * as constants from "@constants";

const app = createApp(App);

app.config.globalProperties.$const = Object.freeze(constants);

app.use(store);

app.mount("#app");

component

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Header",

  computed: {
    tags() {
      return Object.entries(this.$const.TAGS);
    }
  }
});
</script>

Any help would be appreciated.

0

1 Answer 1

34

You can augment the @vue/runtime-core TypeScript module in your application:

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $const: Record<string, unknown>;
  }
}

export {}  // Important! See note.

Here is a documentation: ComponentCustomProperties

Important note: TS module augmentation works correctly only when it is placed in a module.

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

Therefore the file must contain at least one top-level import or export statement, even if empty one (as in the example above) - Type Augmentation Placement

Sign up to request clarification or add additional context in comments.

5 Comments

Why '@vue/runtime-core' and not 'vue' as stated in the docs?
You should be augmenting vue instead, but there's webstorm bug (maybe same thing in vetur?), and so it's nicer to augment one or both of runtime-core and regular vue
I had to augment '@vue/runtime-core' when using Visual Studio Code.
Adding the export {} breaks my other declare module '*.vue' { import { DefineComponent } from 'vue'; const component: DefineComponent<{}, {}, any>; export default component; }
For those who find this in the future, try vue instead of @vue/runtime-core if you find the latter isn't working – vue was what worked for me.

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.