首页 > 解决方案 > 使用 typescript 3.0.1 项目引用时找不到类型定义

问题描述

我最初有以下项目结构(monorepo)

_app/
_firebase/
_types/
tsconfig.json

在这里,根级别的 tsconfig 用于_app和typescript_firebase项目。_types是一个包含文件的文件夹models.tsstore.ts等等......这些文件只是定义了不同的接口。

我能够使用这些接口,而无需在之前的项目中导入/导出任何内容_app_firebase没有任何问题。

我进行了更改以使用 typescripts v3 项目引用,所以我的应用程序结构现在看起来像这样

_app/
  tsconfig.json
_firebase/
  tsconfig.json
_types/
tsconfig.json

根级别tsconfig.json有以下内容

{
  "compilerOptions": {
    "composite": true
  },
  "references": [
    { 
      "path": "_app" 
    }
  ]
}

其他配置只有简单的选项,如,outDir等...targetlib

现在,如果我_types在任何地方使用文件夹中的接口,_app或者_firebase我收到类似的错误

[ts] 找不到名称“IInventoryModel”。

有什么方法可以保留以前的功能,在没有显式导出/导入的情况下使用这些接口,同时仍然利用新项目的引用功能?

编辑:这是 tsconfig 的示例_app

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "lib": ["es2016"],
    "jsx": "react",
    "outDir": "./dist",
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
  }
}

EDIT文件夹内的 2 个接口_types声明如下,即_types/models.ts

interface ICharacterModel { /* ... */ }

interface IInventoryModel { /* ... */ }

// etc...

标签: reactjstypescripttsconfig

解决方案


对于初学者,_types需要它自己的tsconfig.json并且_app需要引用它。然后,根据文档,看起来神奇的步骤是设置一个outFileon _types。以下配置对我有用:

// _app/tsconfig.json
{
  "compilerOptions": {
    "composite": true,
    "target": "es2016",
    "module": "commonjs",
    "lib": ["es2016"],
    "jsx": "react",
    "outDir": "./dist",
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
  },
  "references": [
    {
      "path": "../_types"
    }
  ]
}

// _types/tsconfig.json
{
    "compilerOptions": {
        "composite": true,
        "outFile": "types.js"
    }
}

推荐阅读