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

TypeScript:使用type导入的命名空间能否重新导出?

是否可以重新导出使用type限定符导入的命名空间?

我们从typescript/lib/tsserverlibrary.js导入tslib命名空间,尝试重新导出其中的tslib.server.protocol子命名空间,同时保留type限定符,初始代码如下:

import type tslib from 'typescript/lib/tsserverlibrary.js';

export type tsp = typeof tslib.server.protocol;

尝试了两种方式,均出现报错:

第一种尝试

export type tsp = typeof tslib.server.protocol;

报错信息:

'tsp'仅指代类型,但此处被用作命名空间。typescript(2702)
原因:typeof tslib.server.protocol仅提取了类型信息,导出的tsp是类型而非命名空间,无法当作命名空间访问其成员。

第二种尝试

export import tsp = tslib.server.protocol;

报错信息:

导入别名无法引用使用'import type'导入的声明。typescript(1380)
原因:import type导入的内容仅存在于TypeScript类型系统中,没有对应的运行时值,而export import属于值层面的导出,无法引用仅类型存在的内容。


可行方案

  1. 仅需类型层面使用:
    保持第一种写法,但导入端只能将tsp作为类型使用(比如类型注解),不能当作命名空间访问:

    // 导出端
    import type tslib from 'typescript/lib/tsserverlibrary.js';
    export type tsp = typeof tslib.server.protocol;
    
    // 导入端
    import type { tsp } from './your-module';
    const foo: tsp.SomeType = ...; // 仅作为类型使用
    
  2. 需要保留命名空间的使用能力:
    必须去掉type限定符,使用普通导入后再重新导出:

    // 导出端
    import tslib from 'typescript/lib/tsserverlibrary.js';
    export import tsp = tslib.server.protocol;
    
    // 导入端
    import { tsp } from './your-module';
    const bar = tsp.someValue; // 可作为命名空间访问值
    type Baz = tsp.SomeType; // 也可作为类型使用
    

    注意:普通导入会引入运行时代码,若仅需纯类型导出,此方案会带来冗余;但如果确实需要命名空间的使用能力,这是唯一可行的方式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:00:47