How to add global interfaces to Nuxt project
Asked Answered
L

3

20

I just started with Nuxt 3 and have been having some trouble with using typescript functionality.

I am trying to build a general NavBar that can have multiple buttons with different links. For this I wanted to make an interface that I can pass as an array to the component.

Something like:

interface Button {
  icon: string,
  link: string
}

Is there some way to make interfaces that are visible throughout my whole project? I can't find a lot about typescript integration for Nuxt.

Lexicon answered 3/5, 2022 at 12:24 Comment(1)
What I do is just a root folder /types with an index.ts that exports every type one by one. This way you can easily include them with import { type, anotherType, an wholeOtherType } from '~/types' without too much work.Crofter
L
20

Thanks to Tea_lover_418, I tried what he suggested in the comment and it works even better with global declaration.

At the root of your project create a directory named types with an index.ts file, add your global types declaration like in the example below. That's it, you don't need to import anything it's available globally.

// ~/types/index.ts

export { };

declare global {
  type SomeType = [boolean, string, number]; 

  interface MyFancyInterface {
    ...
  }

  const enum GlobalConstEnum {
    ...
  }

  ....
}

Lunnete answered 4/8, 2022 at 14:27 Comment(0)
A
11

Few corrections to Fennec answer.

  1. I would add index.d.ts instead of index.ts and ideal case it should be generated.
// ~/types/index.d.ts

export { MyInterface };

declare global {
  interface MyInterface {
        some_field: number
    }
}
  1. To you tsconfig.json you should add includes (plural)
  {
    "extends": "./.nuxt/tsconfig.json",
    "includes": [
      "types/*.d.ts"
    ]
  }
Amias answered 26/6, 2023 at 12:11 Comment(0)
A
-1

One correction to Gleb's answer - "include" should be "includes" (plural)

{
    "extends": "./.nuxt/tsconfig.json", 
    "includes": [ "types/*.d.ts", ] 
}

Singular caused useNuxtApp and other Nuxt features to become 'unknown'. Plural worked perfectly.

Auricle answered 16/12, 2023 at 4:0 Comment(1)
includes (as in plural) is not working for me. Yes, the Nuxt imports (ref, computed, useNuxtApp etc. do not get overwritten, but MyInterface does not get importedEdema

© 2022 - 2024 — McMap. All rights reserved.