javascript - 为什么我的 typescript 接口(interface)被编译为 javascript?

标签 javascript node.js typescript interface

据我了解,接口(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/

相关文章:

javascript - 找不到模块 : Error: Can't resolve 'stream' in 'C:\dev\jszip-test\node_modules\jszip\lib'

typescript - 如何在 TypeScript AMD 模块中定义依赖模块

javascript:获取关联数组中包含重复数据的键

c# - 自定义下拉列表样式(CSS/JS 与 ASP.NET C# 连接)

javascript - 访问嵌套在数组中的对象的特定值

javascript - 使用 Javascript 添加到表格

node.js - 如何在 Winston/Node.js 中设置日志级别

node.js - Stripe - 创建或更新订阅时 PaymentIntent 为空

javascript - 从nodejs中的多部分请求中检索JSON对象

angular - 当验证器设置为 minLength 时空字段控制有效