据我了解,接口(interface)仅与 Typescript 相关,并且 tsc 编译器应该足够聪明,不会在最终输出中将它们转换为 JS 文件。当我编译我的代码时,正在用它编译接口(interface)。为什么是这样?
我的简化项目结构
src/
index.ts
lib/
EventClient.ts
interfaces/
EventClientConfig.ts
它编译成什么
dist/
index.js
lib/
EventClient.js
interfaces/
EventClientConfig.js
我的 tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"outDir": "./dist",
"lib": ["ES6", "DOM"],
"target": "ES2018",
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true,
"baseUrl": ".",
"removeComments": true,
"strict": true,
"typeRoots": ["./node_modules/@types"],
"rootDir": "./src",
"types": [
"node",
"jest-fetch-mock",
"express",
"reflect-metadata"
]
},
"include": ["src"],
"exclude": ["dist", "node_modules", "**/*spec.ts"]
}
一个界面
export interface EventClientConfig {
endpoint: string;
authToken: string;
}
我如何使用界面
import { EventClientConfig } from '../interfaces/EventClientConfig';
const config: EventClientConfig = {
endpoint: '/api',
authToken: '123456'
}
接口(interface)编译成什么
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
在编译的代码中,EventClient.js 没有实际引用 EventClientConfig.js,所以它绝对不是必需的。为什么 Typescript 要将接口(interface)文件编译成 JS?
最佳答案
感谢@AluanHaddad 解决了这个问题,他建议使用 .d.ts 声明文件。我已更改所有接口(interface)文件名,以便它们以 .d.ts 结尾,并且不再包含在输出中。
关于javascript - 为什么我的 typescript 接口(interface)被编译为 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61681780/