有没有一种方便的方法可以在模块内访问全局变量,而不会出现编译器错误,比如下面使用的CANVAS_WIDTH?

    export class Bullet {


        x: number = 22;
        y: number = 22;

        constructor (speed: number) {
            this.xVelocity = speed;
        }

        inBounds() {
            return this.x >= 0 && this.x <= CANVAS_WIDTH &&
                this.y >= 0 && this.y <= CANVAS_HEIGHT;
        };
}
}

推荐答案

你需要将这些属性定义为静态的,然后你可以像这样轻松地访问它,

export class Game {
    static canvas: JQuery;
    static CANVAS_WIDTH: number;
    static CANVAS_HEIGHT: number;
    bullet: Bullet;

    constructor(canvasElem: JQuery) {
        Game.canvas = canvasElem;
        Game.CANVAS_WIDTH = Game.canvas.width();
        Game.CANVAS_HEIGHT = Game.canvas.height();
    }
}

export class Bullet {
    x: number = 22;
    y: number = 22;

    public inBounds() {
        // accessing static properties
        return this.x >= 0 && this.x <= Game.CANVAS_WIDTH && this.y >= 0 && this.y <= Game.CANVAS_HEIGHT;
    }
}

这将编译为:

define(["require", "exports"], function(require, exports) {
    var Game = (function () {
        function Game(canvasElem) {
            Game.canvas = canvasElem;
            Game.CANVAS_WIDTH = Game.canvas.width();
            Game.CANVAS_HEIGHT = Game.canvas.height();
        }
        return Game;
    })();
    exports.Game = Game;

    var Bullet = (function () {
        function Bullet() {
            this.x = 22;
            this.y = 22;
        }
        Bullet.prototype.inBounds = function () {
            // accessing static properties
            return this.x >= 0 && this.x <= Game.CANVAS_WIDTH && this.y >= 0 && this.y <= Game.CANVAS_HEIGHT;
        };
        return Bullet;
    })();
    exports.Bullet = Bullet;
});
//# sourceMappingURL=dhdh.js.map

Typescript相关问答推荐

Angular -使用Phone Directive将值粘贴到控件以格式化值时验证器不工作

您可以创建一个类型来表示打字员吗

如何使类型只能有来自另一个类型的键,但键可以有一个新值,新键应该抛出一个错误

Angular中的其他服务仅获取默认值

React typescribe Jest调用函数

在嵌套属性中使用Required

在包含泛型的类型脚本中引用递归类型A<;-&B

通过字符串索引访问对象';S的值时出现文字脚本错误

如何在NX工作区项目.json中设置类似angular.json的两个项目构建配置?

寻址对象中路径的泛型类型

Angular material 无法显示通过API获取的数据

有没有办法防止类型交集绕过联合类型限制?

在TypeScript中扩展重载方法时出现问题

react 路由不响应参数

如何扩展RxJS?

类型分布在第一个泛型上,但不分布在第二个泛型上

Typescript泛型验证指定了keyof的所有键

将带有额外id属性的Rust struct 展平回TypeScript单个对象,以返回wasm-bindgen函数

数据库中的表请求返回如下日期:2023-07-20T21:39:00.000Z 我需要将此数据格式化为 dd/MM/yyyy HH:mm

对象只能使用 Typescript 中另一个对象的键