使用 import 语句会破坏其他 class 引用?

Using an import statement breaks other class references?

作为 关于具体使用 bowser DefinitelyTyped 定义文件的跟进,我按照该问题中答案的指示实施了 import 语句,并取得了进一步的进展。但是现在 TypeScript 编译器抱怨在所有 bowser import 胡说八道之前编译得很好的代码。

假设我有 MyBowserClass.ts:

import bowser = require('bowser');

namespace MyNamespace {
    export class MyBowserClass {
        constructor() {
            var isIos = (typeof bowser.ios === 'undefined') ? false : bowser.ios;
            alert(isIos);

            var myInstance = new MyNamespaceTwo.MyOtherClass(); // typescript compiler complains: Property 'MyOtherClass' does not exist on type 'typeof MyNamespaceTwo'.
        }
    }
}

然后我有 MyOtherClass.ts:

namespace MyNamespaceTwo {
    export class MyOtherClass {
        constructor() {
            alert('otherclass ctor');
        }
    }
}

编译器在这里给我一个错误:

var myInstance = new MyNamespaceTwo.MyOtherClass();

Property 'MyOtherClass' does not exist on type 'typeof MyNamespaceTwo'.

所以我想也许这意味着我还需要导入 MyOtherClass?

我通过更新我的两个文件让它工作:

import bowser = require('bowser');
import otherClass = require('MyOtherClass'); // NEW IMPORT

namespace MyNamespace {
    export class MyBowserClass {
        constructor() {
            var isIos = (typeof bowser.ios === 'undefined') ? false : bowser.ios;
            alert(isIos);

            var myInstance = new otherClass.MyNamespaceTwo.MyOtherClass(); // changed this to prefix with 'otherClass'
        }
    }
}

export namespace MyNamespaceTwo { // made this EXPORT
    export class MyOtherClass {
        constructor() {
            alert('otherclass ctor');
        }
    }
}

这似乎是总计 chaos/craziness。我在这里错过了什么?为什么 bowser 定义文件应该是一个模块(当它包含一个 global/essentially 静态方法名称时??)任何 guidance/help 将不胜感激。

您似乎正在将文件从全局声明文件更改为模块声明文件。

  • a 全局声明文件 使其中声明的类型在整个项目中都可以访问,而无需导入任何内容。全局声明文件永远不能从另一个文件导入。它们也从不导出,因为其中声明的类型随处可用。

    例如。使用 redux 的项目可以声明一个 SpecialAction 然后可以在项目的任何地方使用:

    // index.d.ts
    interface SpecialAction {
      type: string
      isSpecial: boolean
    }
    
    // src/app.ts
    let theAction: SpecialAction = {
      type: 'SPECIAL',
      isSpecial: true
    }
    
  • a 模块声明文件 将特定类型导出到模块,因此导出可以导入项目的其他地方。一旦在声明文件中导入或导出,它就变成了模块声明文件。

    // index.d.ts
    import { Action } from 'redux'
    export interface SpecialAction extends Action {
      isSpecial: boolean
    }
    
    // src/app.ts
    import { SpecialAction } from '../index'
    let theAction: SpecialAction = {
      type: 'SPECIAL',
      isSpecial: true
    }
    

希望对您有所帮助? ¯\_(ツ)_/¯