2016-02-05 50 views
0

我想將一個抽象類擴展到另一個類,但爲了更方便,我需要在另一個文件中有這個抽象類。不幸的是,它引發了我難以理解的運行時錯誤。從Typescript中的另一個模塊的繼承類

這工作:

abstract class Item{ 
    constructor(){ 
     console.log("I am an Item"); 
    } 
} 

export class Folder extends Item{ 
    constructor(){ 
     super(); 
    } 
} 

登錄:

I am an Item 

這不:

module MyModule{ 
    export abstract class Item{ 
     constructor(){ 
      console.log("I am an Item"); 
     } 
    } 
} 

export class Folder extends MyModule.Item{ 
    constructor(){ 
     super(); 
    } 
} 

編譯,但拋出:

Uncaught TypeError: Cannot read property 'prototype' of undefined 

有誰知道發生了什麼事?

+0

問題似乎來自出口抽象類。我剛發現的一個解決方案是聲明一個var,它將指向這個抽象類: export var ItemClass = Item; then: export class Folder extends MyModule.ItemClass; 它看起來像一個有效的解決方法嗎? – Kromah

回答

0

源文件中的頂級導出(在這種情況下爲export class Folder)意味着TypeScript將該文件視爲外部模塊,但除非您在編譯TypeScript時應指定模塊格式應發出error TS1148: Cannot compile modules unless the '--module' flag is provided.因此,我如果你只使用內部模塊,你會如何設法編譯這些代碼片段。

我強烈建議使用外部模塊(其中每個.ts文件本身就是一個模塊)並完全避免名稱空間(以前稱爲內部模塊)。

這裏是你的代碼是什麼樣子什麼也沒有,但外部模塊:

// mymodule.ts 
export abstract class Item { 
    constructor() { 
    console.log("I am an Item"); 
    } 
} 

// folder.ts 
import * as MyModule from './mymodule'; 

export class Folder extends MyModule.Item { 
    constructor() { 
    super(); 
} 

但是,如果你想堅持使用命名空間,而不是,你可以這樣做:

namespace MyModule { 
    export abstract class Item { 
    constructor() { 
     console.log("I am an Item"); 
    } 
    } 
} 

namespace MyOtherModule { 
    export class Folder extends MyModule.Item { 
    constructor() { 
     super(); 
    } 
    } 
} 
+0

非常感謝您的回答。它確實有效,但這是一個合理的選擇嗎?我的ts項目包含許多用內部模塊組織的文件。將所有內容作爲外部模塊導入,似乎是一件瘋狂的工作。根據http://typescript.codeplex.com/wikipage?title=Modules%20in%20TypeScript&referringTitle=TypeScript%20Documentation,「在兩種情況下使用外部模塊:node.js和require.js。不使用node.js的應用程序或者require.js不需要使用外部模塊,並且最好使用上述內部模塊概念進行組織。「 你覺得呢? – Kromah

+0

@Kromah這個特別的建議是過時的,我相信現在的共識是使用外部模塊和模塊打包器(如果你想把所有東西都捆綁到一個或多個文件中)。不過,我已經擴展了我的答案以涵蓋名稱空間方法。 FYI TypeScript從CodePlex轉移到Github前一段時間,該文檔的特定部分現在可以在[handbook](http://www.typescriptlang.org/Handbook)中找到,它也有點過時,有一個Wiki中的幾個頁面概述了每個TypeScript版本的主要變化。 –

相關問題