【问题标题】:TypeScript casting with modules带有模块的 TypeScript 强制转换
【发布时间】:2012-11-16 19:41:20
【问题描述】:

如何使用导出的类转换变量的类型?比如这样:

GameManager.ts:

export class GameManager {}

玩家.ts:

private _manager: GameManager;

当我使用 /// <reference path="GameManager.ts" /> 时,我收到一条错误消息,提示 GameManager 超出范围或类似的东西。这究竟是如何工作的?

【问题讨论】:

    标签: node.js casting module typescript


    【解决方案1】:

    对于内部模块,您必须将导出的类包装在模块中,因此 GameManager.ts 文件应为:

    module Game
    {
        export class GameManager{}
    }
    

    现在您可以通过以下方式访问 GameManager 类

    Game.GameManager

    【讨论】:

      【解决方案2】:

      这里有几种情况,取决于export class GameManager {} 行的位置:

      选项 1:您正在使用“外部”模块(即您在顶层有任何 export 声明)。

      在这种情况下,您应该删除reference 标签并改为:

      import Manager = module("GameManager"); // N.B. this is the filename, not the class name
      ...
      private _manager: Manager.GameManager;
      

      选项 2:您正在使用“内部”模块(即您的 export classmodule 块内,但不在 export module 块内)

      在这种情况下,你应该保留你的/// <reference... 标签并写:

      private _manager: MyGame.Manager; // N.B. Assuming here that 'GameManager' lives inside 'module MyGame { ... }'
      

      这可能是您实际上并不希望在您的课程中使用 export 关键字 - 如果您这样做,您根本不需要限定它(假设在顶层没有其他东西被导出)。

      【讨论】:

      • 好的,我这样做了,现在我得到了奇怪的“属性不存在”错误。 The property sendToAllButOrigin' does not exist on value of type "GameManager"`
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多