首页 > 解决方案 > 如何在 Vue SFC 中使用 Typescript 全局类型声明?

问题描述

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

全球.d.t​​s

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

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

杂项

const answer: Nullable<Answer> = null;

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

组件.vue

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

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

三重斜线也不起作用:

<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>

有什么解决办法吗?

标签: typescriptvuejs2

解决方案


我通过将路径添加到我的目录中的global.d.ts文件来解决了这个问题tsconfig.json

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

推荐阅读