TypeScript错误:无法读取未定义的属性“REPOSITORY”

4

作为一个熟悉面向对象设计但不熟悉TypeScript的人,我不理解发生了什么。

文件 application.ts

class
    APPLICATION{

        constructor(){
            console.log("constructor APPLICATION")
            this.database = new REPOSITORY
        }

        database: REPOSITORY
}

new APPLICATION

import { REPOSITORY } from "./repository"

文件 repository.ts

export

class
    REPOSITORY {

        constructor() {
            console.log("constructor de REPOSITORY")
        }

}

我遇到了错误

    this.database = new repository_1.REPOSITORY;
                                    ^

类型错误:无法读取未定义的属性“REPOSITORY” 在新应用程序中(Z:\ Documents \ Phi \ Developpement \ TypeScript \ test \ application.js:6:41)

有什么想法吗?

3个回答

2

您是完全正确的!我之前认为编译器是两遍扫描,而且这些语句的顺序是没有要求的。既然我认为这个导入/导出机制应该是自动的,我更喜欢将其隐藏在代码末尾!太糟糕了!

谢谢你。


1

您的REPOSITORY导入语句出现在APPLICATION构造函数中使用REPOSITORY之后,这意味着它在构造函数中尚未定义(导入语句的变量赋值不会被提升)。您需要在使用之前导入:

import { REPOSITORY } from "./repository"

class APPLICATION {
    constructor(){
        console.log("constructor APPLICATION")
        this.database = new REPOSITORY();
    }
    database: REPOSITORY
}

0

我不相信导入会被提升。尝试将import { REPOSITORY } from "./repository"移到你的代码上方。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接