首页 > 解决方案 > 访问同级命名空间打字稿时遇到问题

问题描述

假设我有一个项目,我把它分成一堆部分,可能看起来像这样:

Project
    Core
        entity.ts
        assert.ts
    Math
        matrix.ts

Assert.ts 可能如下所示:

namespace Project.Core {
    export const assert = (expression: any, message: string) => !expression && console.error(message)
}

太好了,没有什么疯狂的事情发生,现在看看 entity.ts:

namespace Project.Core {
    export class Entity {
        id: string;
        constructor(id: string) {
            assert(!globalIDDatabase.has(id), "Entity with duplicate ID was created")
            this.id = id;
        } 
    }
}

这也有效,不需要导入任何东西,assert 在Project.Core命名空间中,所以它会自动被拾取,但是如果我们首先在 matrix.ts 中添加如下:

namespace Project.Math {
    class Matrix {
        arr: number[][];
        // Math stuff
    }
}

然后尝试在 entity.ts 中使用它:

namespace Project.Core {
    export class Entity {
        id: string;
        transform: Project.Math.Matrix;
        constructor(id: string) {
            assert(!globalIDDatabase.has(id), "Entity with duplicate ID was created")
            this.id = id;
        } 
    }
}

TSC 找到Project命名空间,但它会在Math子命名空间出错。如果我在文件顶部添加一个空白namespace Project.Math{},它会将问题转移到 Matrix 上,如下所示:

Property "Matrix" does not exist in namespace Project.Math

如何在保持这种结构的同时访问矩阵类?

标签: typescriptnamespacesjavascript-namespaces

解决方案


推荐阅读