Blog>
Snippets

Provide/Inject with TypeScript Support

Present how to add type annotations when using provide/inject in a TypeScript-enabled Vue.js 3 project for improved development experience and type-checking.
import { inject, provide, defineComponent } from 'vue';
import type { InjectionKey } from 'vue';

// Define a symbol as the injection key
const key: InjectionKey<string> = Symbol('myString');

// Define the provider component
export default defineComponent({
  setup() {
    // Provide the value with the type-safe key
    provide(key, 'Hello World');
  }
});
This piece of code creates a provider component in a Vue.js 3 project with TypeScript. It imports necessary functions from 'vue', defines a TypeScript 'InjectionKey', and uses it to provide a value in a type-safe way within the 'setup' function of the component.
import { defineComponent, inject } from 'vue';
import type { InjectionKey } from 'vue';

// Define a symbol as the injection key
const key: InjectionKey<string> = Symbol('myString');

// Define the injector component
export default defineComponent({
  setup() {
    // Inject the value with the type-safe key
    const injectedValue = inject(key);

    if (injectedValue) {
      // Use the injected value, knowing it is a string
      console.log(injectedValue);
    }
  }
});
This piece of code creates an injector component where it uses 'inject' with the type-safe key to consume the provided value. It checks if the value is not 'undefined' before using it, allowing TypeScript to infer the correct type of 'injectedValue'.