You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中找不到@types/spotify-api的SpotifyApi命名空间报错

问题:Angular项目导入API项目类型时找不到SpotifyApi命名空间

项目背景

  • 同时维护一个API项目和一个Angular客户端项目
  • Angular项目通过tsconfig.json的paths配置,用@shared/*别名导入API项目的../api/src/*文件,此前该配置运行正常

Angular项目的tsconfig.json配置如下:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "useDefineForClassFields": false,
    "lib": ["ES2022", "dom"],
    "paths": {                          /* <-- 注意此处配置 */
      "@shared/*": ["../api/src/*"]
    }
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

问题触发场景

API项目中有../api/src/schema/request.d.ts文件,内容如下:

export namespace Request {
  export interface GetPlaylistTracks {
    Params: {
      playlistId: string;
    };
    ResBody: SpotifyApi.PagingObject<any> | undefined;
    ReqBody: {};
    ReqQuery: {
      offset: string;
      limit: string;
    };
  }
}

在Angular项目中执行以下导入语句时出现错误:

import { Request } from '@shared/schema/request';

错误信息

Error: ../api/src/schema/request.d.ts:26:14 - error TS2833: Cannot find namespace 'SpotifyApi'. Did you mean 'Spotify'?

26     ResBody: SpotifyApi.PagingObject<any> | undefined;

已知情况

  • SpotifyApi命名空间来自@types/spotify-api依赖
  • API项目中使用该依赖完全正常
  • 两个项目的package.json都已安装该依赖:
{
  ...
  "devDependencies": {
    ...
    "@types/spotify-api": "^0.0.22"
  }
}

解决方法

方法1:显式声明要加载的类型

在Angular项目的tsconfig.json的compilerOptions中添加types数组,指定加载spotify-api类型:

"compilerOptions": {
  // 其他配置不变
  "types": ["spotify-api"]
}

TypeScript默认不会自动加载所有@types包,跨项目导入类型时,显式声明能确保编译器找到对应的命名空间。

方法2:调整Angular的文件包含范围

在Angular项目的tsconfig.json中添加include配置,包含API项目的类型文件:

"include": [
  "src/**/*",
  "../api/src/**/*.d.ts"
]

确保编译器能扫描到API项目中依赖的类型定义文件。

方法3:将API项目作为本地依赖引入

如果API项目可以打包成npm包,通过npm link或者在Angular项目的package.json中添加本地依赖(比如"api-project": "file:../api"),这样TypeScript会自动解析API项目的依赖,无需手动处理跨项目类型引用。

内容的提问来源于stack exchange,提问作者striderhobbit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 19:23:07