5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Nuxtでグローバルな型定義

Last updated at Posted at 2023-08-08

はじめに

Nuxt3でTypeScriptの型チェックを有効にした際、グローバルな型定義をどこに配置すればいいのかわからなかったので苦労しました。
ここではd.tsファイルを使ってグローバルな型定義を行うための設定方法を共有しようと思います。

環境

$ npx nuxi -v
Nuxi 3.6.5
$ npx vue-tsc -v
Version 5.1.6

結論

こちらにもあるように、ルートのtsconfig.jsoncompilerOptions.pathsなどを書くと、nuxiが用意してくれる設定が上書きされてしまいます。
代わりに、ルートのnuxt.config.tsに以下のように書くことで解決しました。

export default defineNuxtConfig({
  ...
  alias: {
    "*": "types/*",
  },
})

型定義の例

以下のように書くと、Vueファイル内のscriptダグやtemplateタグでPost型が使えます。

~/types/post.d.ts
interface Post {
    id: number,
    title: string,
    content: string,
}

おまけ

プラグインの型定義をする場合はこのようになると思います。

~/plugins/hello.ts
declare global {
    interface NuxtApp {
        $hello: (name: string) => string,
    }
}

export default defineNuxtPlugin((nuxtApp) => {
    return {
        provide: {
            hello(name: string) {
                return `Hello ${name}!`
            }
        }
    }
})

おわりに

VSCodeのエラーが消えてくれませんが、いつか解決策を見つけられればと思います。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?