2016-08-24 35 views
0

作爲關於使用bowser DefinitelyTyped定義文件具體使用my previous question的後續,我實現了import語句,按照該問題中的答案指示並進一步獲得。但是現在,TypeScript編譯器抱怨在所有bowser導入廢話之前編譯完美的代碼。使用導入語句會破壞其他類的引用嗎?

比方說,我有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'); 
 
     } 
 
    } 
 
}

這似乎是亂了套/瘋狂。我在這裏錯過了什麼?爲什麼bowser定義文件無論如何都是模塊(當它由全局/基本上靜態的方法名稱組成時)?任何指導/幫助將不勝感激。

+0

您可以更新問題,而不是試圖描述您所做的更改,請在更改後發佈代碼?這將使它更容易理解。 –

+0

@NitzanTomer你去了。希望有所幫助。 –

回答

2

看起來好像你正在將你的文件從全局聲明文件更改爲模塊聲明文件。

  • 一個全局聲明文件使得它宣佈整個項目訪問,而無需輸入任何東西的類型。全局聲明文件不能從其他文件導入。他們也從不出口,因爲在其中宣佈的類型在任何地方都可用。

    例如,使用redux一個項目可以申報,然後可以在項目的任何地方使用的SpecialAction

    // index.d.ts 
    interface SpecialAction { 
        type: string 
        isSpecial: boolean 
    } 
    
    // src/app.ts 
    let theAction: SpecialAction = { 
        type: 'SPECIAL', 
        isSpecial: true 
    } 
    
  • 一個模塊聲明文件出口特定類型的模塊,所以出口可以在其他地方在項目中導入。只要您在聲明文件中導入或導出,它就會成爲模塊聲明文件。

    // 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 
    } 
    

我希望這可以幫助? ¯\_(ツ)_/¯

+1

我想這有助於回答我的問題:'只要你在一個聲明文件中導入或導出,它就會成爲一個模塊聲明文件.'我的'導入bowser = require('bowser');'線正在使我的文件成爲「模塊聲明「。我不期望。我對這一切感到非常沮喪,猜想是時候讓我讀一讀了。 –

+0

這就是爲什麼我在最終得到它之前已經失去了無數個小時。我很高興我可以幫忙! –

+0

非常感謝Pelle,但是我如何解決這個問題,我想在我的導出類中訪問'moment'(這是爲了支持@types)?在將'import moment = require('moment');'添加到文件頂部時,我遇到同樣的問題。 – GONeale