2016-02-26 76 views
1

代码编译并运行,但是我发现类型检查出现错误,并且出现大量文件和变量。这是一个例子。在同一目录中找不到模块的名称

Test1.ts

import Test2 = require('./Test2'); 

class Test1 { 
    test2: Test2; 
    constructor() { 
     this.test2 = new Test2(); 
    } 
} 

console.log(new Test1()); 

Test2.ts

export = class Test2 { 
    prop: number; 
    constructor() { 
     this.prop = 5; 
    } 
} 

运行tsc --module commonjs Test1.ts给了我这个错误:

Test1.ts(4,12): error TS2304: Cannot find name 'Test2'. 

和运行代码输出:

Test1 { test2: Test2 { prop: 5 } } 

我在做什么错在这里?

回答

1

不要使用export =/import =语法。它能够更好地做到这一点是这样的:

Test1.ts

import {Test2} from './Test2'; 

class Test1 
{ 
    test2: Test2; 
    constructor() { 
     this.test2 = new Test2(); 
    } 
} 

console.log(new Test1()); 

Test2.ts

export class Test2 
{ 
    prop: number; 
    constructor() 
    { 
     this.prop = 5; 
    } 
} 
+0

有趣的....这工作。为什么这更好?我很高兴这个作品,但我很好奇为什么另一个人不愿意。 – adamk33n3r

+0

我发现一个缺点是,它使得需要编译的文件从一个香草的JavaScript令人厌恶,因为你必须通过命名空间像'var Test1 = require('./ Test1')。Test1' – adamk33n3r

+0

要解决您的问题通过坚持原来的代码我会设置出口像这样:export = Test2; 看看这里的一些很好的解释:http://stackoverflow.com/questions/35455720/proper-explanation-for-nodejs-typescript-export-import – Amid

相关问题