在TypeScript文件中导入接口时,不会创建新的目录结构

前端开发 2026-07-11

我正在开发一个通过Node.js使用服务器端数据并通过webview访问的网页应用。我有两个目录,分别放有TypeScript文件,一个用于服务器端,一个用于客户端:

/ts
  /pub
    /tsconfig.json
    /foo.ts
    /bar.ts
    ...
  /sys
    /tsconfig.json
    /ApiResponse.ts
    /index.ts
    ...

pub 用于浏览器加载的JavaScript;sys 由Node运行。现在,ApiResponse.ts 看起来是这样的:

export interface ApiResponseData {
  code?: number,
  title: string,
  ...
}

是否可以在 pub 内使用 ApiResponseData 接口,而不尝试把 ApiResponse.ts 转换成JavaScript文件?通常来自 pub 的tsconfig的 JavaScript编译结果是这样的:

/res
  /js
    /foo.js
    /bar.js
    ...

但当我在(例如)foo.ts 中使用 import { ApiResponse } from '../sys/ApiResponse.ts 时,看起来是这样的:

/res
  /js
    /pub
      /foo.js
      /bar.js
      ...
    /sys
      /ApiResponse.js

有没有办法在 pub 内获取 ApiResponseData 接口,而不导致上述情况发生?

解决方案

What you did works, but it’s not the best practice for this situation.

Renaming the file to .d.ts turns it into a global type declaration. That means the type becomes available everywhere without imports, which can lead to naming conflicts and makes it harder to track where types are coming from.

.d.ts 文件主要用于库类型定义或声明外部/全局类型,而不是用于普通应用级别的类型共享。

A better approach is to use import type.

Keep your file as:

// sys/ApiResponse.ts
export interface ApiResponseData {
  code?: number;
  title: string;
}

Then in your pub code:

import type { ApiResponseData } from "../sys/ApiResponse";

This way, the type is available where needed, no JavaScript is generated for the import, and your code remains modular and explicit.

Another cleaner approach is to move your shared types into a dedicated folder like:

/ts
  /shared
    ApiResponse.ts
  /pub
  /sys

Then both sides can import from:

import type { ApiResponseData } from "../shared/ApiResponse";

This avoids mixing server-specific files with shared contracts

Avoid using .d.ts for internal sharing, use import type or a shared types module instead.

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章