如何在Vue SFC中使用Typescript全局类型声明?

时间:2020-11-03 12:18:14

标签: typescript vuejs2

Vue2 + Typescript项目中,我有global.d.ts文件,其类型如下:

global.d.ts

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

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

misc.ts

const answer: Nullable<Answer> = null;

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

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

对此有什么解决办法吗?

1 个答案:

答案 0 :(得分:0)

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

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