【问题标题】:Export TS Types with CommonJS Require使用 CommonJS 导出 TS 类型 Require
【发布时间】:2016-08-19 01:30:36
【问题描述】:

给定文件 A.ts:

interface B {};
export = {};

和文件 C.ts:

import A = require("./A");
var c: B; // Typescript error: Cannot find name

如何使在 A.ts 中声明的接口在 C.ts 中可见同时仍使用 CommonJS 导入样式(即require

我尝试过var c: A.B,但这不起作用。

【问题讨论】:

    标签: node.js typescript commonjs


    【解决方案1】:

    你应该对以下结构没问题:

    A.ts

    export interface A 
    {
        SomeProperty: number;
    }
    

    C.ts

    import { A } from './A';
    
    var x: A = {SomeProperty: 123}; //OK
    var x1: A = {OtherProperty: 123}; //Not OK
    

    更新

    你也可以这样写定义文件:

    A.d.ts

    interface B 
    {
        SomeProperty: number;
    }
    

    C.ts

    /// <reference path="A.d.ts" />
    
    var c: B;
    c.SomeProperty; //OK
    

    【讨论】:

    • 谢谢,但正如问题中所述,我无法摆脱 CommonJS 导入系统(即require)。我需要一种方法让它在不改变我的导入风格的情况下工作。
    • 我正在使用import { A } from './A' 语法,在针对 commonjs 的项目中没有任何问题 - 为什么不能使用它?
    • 因为我导入的文件主要使用module.exports,而且更改它们太麻烦了,所以它们是可接受的打字稿模块。
    • 所以你的意思是你无法改变A.ts的结构?
    • 我无法更改 A.ts 的导出结构,但由于我刚刚添加类型信息,我可以更改我声明接口的方式。
    【解决方案2】:

    export = 语法指定从 模块。这可以是类、接口、命名空间、函数或 枚举。

    来自https://www.typescriptlang.org/docs/handbook/modules.html

    所以现在你导出空类。

    尝试文件 A.ts:

    interface B {};
    export = B;
    

    和文件 C.ts:

    import B = require("./A");
    var c: B;
    

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 2022-08-10
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 2018-03-16
      相关资源
      最近更新 更多