如何在 Vue SFC 中使用 Typescript 全局类型声明? [英] How to use Typescript global types declarations in Vue SFC?

查看:135
本文介绍了如何在 Vue SFC 中使用 Typescript 全局类型声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Vue2 + Typescript 项目中,我有 global.d.ts 文件,其中包含一些类似的类型:

In Vue2 + Typescript project I have global.d.ts file with some types like that:

global.d.ts

type Nullable<T> = T | undefined | null;

在常规 .ts 文件中使用时,它工作正常(没有明确类型导出/导入):

It works fine (without explicitly types export/import) when using in regular .ts files:

misc.ts

const answer: Nullable<Answer> = null;

但它在 .vue 文件中不起作用:

But it doesn't work inside .vue files:

component.vue

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  data: () => ({
    answer: null as Nullable<Answer> // 'Nullable' is not defined
  })
});
</script>

三重斜线的东西也不起作用:

Tripple slash thing doesn't work too:

<script lang="ts">
/// <reference path="../../types/global.d.ts" />

import Vue from 'vue';

export default Vue.extend({
  data: () => ({
    answer: null as Nullable<Answer> // 'Nullable' is not defined
  })
});
</script>

有什么解决办法吗?

推荐答案

我通过在 tsconfig.jsonglobal.d.ts 文件添加到我的目录的路径来解决这个问题>:

I solved that by adding path to my directory with global.d.ts file in tsconfig.json:

{
  "compilerOptions": {
    "typeRoots": [
      "./types"
    ]
  }
}

这篇关于如何在 Vue SFC 中使用 Typescript 全局类型声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆