typescript - 为什么找不到接口类型是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
- 如果您想将类型定义放在其他地方怎么办?
解决方案
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
推荐阅读
- python - Python openpyxl表格样式将表格转换为范围
- javascript - 使用 JS 在硬件中设置硬件配置位
- huawei-mobile-services - 由于 Skybox 制作程序未与开发文档中的示例代码一起发布,因此无法集成 HMS 计算机图形套件示例代码
- zillow - Zillow API 返回 410 响应
- java - 在Java中,变量或参数可以设置子类的父类吗?
- asp.net - "ErrorMessage":"找不到 ABCGeckoWP.exe。"
- php - 随机替换字符串中的单词
- c++ - 在什么情况下 C++11 = 默认构造函数与不带参数和空主体的构造函数不同?
- roblox - workspace.Tool.Handle.Script6:无效参数#3(需要 Vector3,得到实例)
- android - Android 的 CameraX/Camera2 可以同时处理 2 个预览或/和 2 个记录吗?