Reputation: 1825
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.
Upvotes: 9
Views: 17108
Reputation: 700
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
orexport
is considered a module. Conversely, a file without any top-levelimport
orexport
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
Upvotes: 31