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

TypeScript接口导入报错:无法将命名空间用作类型的解决方案咨询

TypeScript接口导入报错解决方案

不需要移除tsconfig.json中的preserveValueImports和isolatedModules配置,用正确的类型导入语法就能解决问题:

正确的导入方式

直接使用类型命名导入语法:

import type { custom } from 'commonlib';

之后就能正常使用接口定义类型:

let customObj: custom;

错误原因解析

  • 第一种导入方式import type custom from 'commonlib'是默认导入语法,但你的接口是命名导出,并非默认导出,TypeScript会将其识别为命名空间,因此抛出Cannot use namespace 'custom' as a type错误。
  • 第二种导入方式import {custom} from 'commonlib'是普通值导入,而custom是类型接口。当preserveValueImports和isolatedModules同时启用时,TypeScript强制要求类型必须通过类型专属导入语法引入,因此抛出类型导入方式错误的提示。

可选优化(非必须)

可以在导出环节明确标注类型导出,让代码更清晰:
修改index.ts的导出语句为:

export type { custom } from './assets/custom';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:15:34