首页 > 解决方案 > 为什么找不到接口类型是Typescript文件

问题描述

编辑:我正在更新这个问题,因为最初我误解了 *.d.ts 文件的用途。问题要么是“类型空间”与“值空间”之一,要么是编译器找不到接口定义。

我创建了一个空的 TypeScript 项目:

 npm i typescript --save-dev
 npx tsc --init

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": [
    "src/**/*.ts",
    "backend_types/**/*.ts"
  ]
}

我相信默认的导入策略是 Node?

我创建了src/backend_types/relays.ts

export interface Relay {
  Name: string;
}

export function newRelay(): Relay {
  const relay: Relay = {
    Name: '',
  };
  return relay;
}

并创建src\main.ts

import { Relay, newRelay } from 'relays'

let relay: Relay = newRelay()

console.log(relay)

现在,当我编译代码时,tsc 找不到 Relay 类型:

> npx tsc
src/main.ts:1:33 - error TS2307: Cannot find module 'relays' or its corresponding type declarations.

1 import { Relay, newRelay } from 'relays';
                                  ~~~~~~~~

确实,如果我查看从relays.ts函数生成的 javascript,但 Relay 类型不存在。这是有道理的,因为“类型”在 javascript 中不存在,只存在于 typescript 中,并且接口是一种类型。我显然混淆了“类型空间”和“价值空间”。

我的问题是:我什至无法在 main.ts 中创建接口类型 Relay 的“值”实例,因为编译器似乎找不到类型定义。我需要在 tsconfig.json 中进行哪些更改才能让编译器找到该接口定义?如果我使用--traceResolution开关,输出中的每一行都会显示一个路径,包括node_modules- 如果您想将类型定义放在其他地方怎么办?

标签: typescript

解决方案


In case of using command line (cli), you won't be able to give both file option and tsconfig.json file (via --project option) which means if you provide your file main.ts, you must have to provide your typing for replays as well but it seems to be hard to give 2 files at the same time (you could find out more about pattern to include them both)

Anyway I would suggest you to follow up 2 either options:

  • Put things into configuration file using include option: tsconfig.json
{
  "compilerOptions": {
    // ...
  },
  "include": [
    "src/**/*.ts"
  ]
}

Then you just simply run: npx tsc without passing anything else

  • Still passing files via CLI but you should put them into a dir so it's easier to pass together for example:
- src
-- main.ts
-- replays.d.ts

Then you run them all:

npx tsc src/*

PS: keep in mind, the tsconfig has no effect in this case


推荐阅读