【问题标题】:Cannot find name of module in same directory在同一目录中找不到模块的名称
【发布时间】:2023-03-13 08:38:01
【问题描述】:

代码编译并运行,但类型检查出现错误,导致大量文件和变量爆炸。这是一个例子。

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

我在这里做错了什么?

【问题讨论】:

    标签: typescript


    【解决方案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;
        }
    }
    

    【讨论】:

    • 有趣....这行得通。为什么这样更好?我很高兴这行得通,但我很好奇为什么另一个没有
    • 我发现的一个缺点是,它需要从香草 javascript 编译的文件令人恶心,因为你必须通过像 var Test1 = require('./Test1').Test1 这样的命名空间
    • 要通过坚持原来的 wy 来修复你的代码,我会这样设置 export:export = Test2;看看这里的一些很好的解释:stackoverflow.com/questions/35455720/…
    • 那个链接非常有用!非常感谢! :)
    猜你喜欢
    • 2012-10-26
    • 1970-01-01
    • 2021-09-24
    • 2017-12-01
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    相关资源
    最近更新 更多