【问题标题】:typescript: exporting types when using 'export =' syntax打字稿:使用'export ='语法时导出类型
【发布时间】:2021-05-24 15:07:18
【问题描述】:

我需要向使用typescript export = syntax 的代码库添加一个功能。代码导出一个函数并向其添加属性:

const f = () => {};
f.someVal = 123;
f.someFunc = () => {};
export = f;

所以用户可以直接用CommonJS\ES风格导入函数:

const f = require('./my_module');
import f from './my_module'; // with esModuleInterop: true

但他也可以在需要的时候导入属性:

import { someVal, someFunc } from './my_module';

我也想导出一个类型,例如该模块的用户应该能够:

import type { SomeInterface } from './my_module';

如何使用 typescript 的 export = 语法导出类型?

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    您可以使用命名空间来做到这一点:

    namespace f {
      export const someVal = 123;
      export const someFunc = () => {};
    
      export type Test = { hello: string };
    }
    export = f;
    

    编辑:我刚刚意识到你想做的事情是不可能的。你不能在常量上有类型。 GitHub (https://github.com/microsoft/TypeScript/issues/18163) 中已经存在问题,但尚未实施。

    【讨论】:

    • 谢谢,但现在 f 不是函数,而是命名空间
    • 我尝试了编辑并得到Cannot redeclare block-scoped variable 'f'。也许我需要以某种方式配置 tsc 才能工作?
    • 需要用var声明
    • @AluanHaddad 谢谢,我改成了 var,现在 tsc 说:“错误 TS2300:重复标识符 'f'。”
    猜你喜欢
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    相关资源
    最近更新 更多