How to use auto-import on interface or type? [nuxt 3] – Typescript

by
Ali Hasan
nuxt.js nuxt3 react-typescript vuejs3

Quick Fix: Declare the auto-import folder for your folder type in nuxt.config.ts:

  imports: {
        dirs: ['types/*.ts', 'store/*.ts', 'types/**/*.ts'],
      },

The Problem:

Automatically import types defined in an external TypeScript file into both TypeScript and Vue files in a Nuxt 3 application.

The Solutions:

Solution 1: Declare auto-import folder

To auto-import custom types or interfaces, specify the directory containing the types in `nuxt.config.ts` under the `imports` object:

// nuxt.config.ts
imports: {
  dirs: ['types/*.ts', 'store/*.ts', 'types/**/*.ts'],
},

This will automatically import all types defined in the specified directories, allowing you to use them in both TypeScript and Vue files without explicit imports.

Solution 2: Using Global Declarations

To auto-import types or interfaces on both TypeScript and .vue files, you can declare them globally using a dedicated “types” folder. Here’s how:

  1. Create a file named "whatever.d.ts" or "whatever.ts" in the "types" folder. In this file, declare the types or interfaces you want to make globally available.

  2. In the "types" file, use the declare global syntax to declare global types. For example:

// types/whatever.d.ts or types/whatever.ts

declare global {
  type ImageDocument = {
    buildId: string
    links: string[]
  }
  
  type InventoryDocument{
    buildId: string
    block: string
    count: number
  }
}

export {};
  1. In your TypeScript and .vue files, you can now use the declared types without needing to import them explicitly. For example, in a .vue file:
// components/foo.vue
<script setup lang="ts">
const props = defineProps<{ image: ImageDocument }>();
</script>

Q&A

How to automatically import type in .vue file?

You can use imports in nuxt.config.ts. Specify directories to be scanned for auto-import of types.

How to globally declare a type that’s avaiable in .vue and .ts files?

Declare a *.d.ts or *.ts file in the types directory, and declare your types in the global namespace.

Video Explanation:

The following video, titled "Nuxt 3: Auto Imports Explained - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Today we highlight one of the coolest feature of Nuxt 3: auto-imports for everything. Want to learn about them or understand how Nuxt is ...