【问题标题】:Typescript type guard through in operator通过 in 运算符的 Typescript 类型保护
【发布时间】:2017-09-11 08:12:42
【问题描述】:

我正要为此在 github 上发布一个问题,但我想我会先在这里问。

我正在为我正在使用打字稿编写的游戏开发组件实体系统。 javascript 中的组件实体系统和(据我所知)打字稿往往不是很安全,我有一个想法来尝试解决这个问题。

我目前的计划是让每个依赖于多个组件的系统公开一个实体类型,该类型将具有该系统处理的实体应具有的许多属性。然后,我将在一个中心位置将所有各种实体类型收集到一个组合的实体联合类型中。

export type Entity =
    CameraManagerEntity |
    CollisionManagerEntity |
    HoleManagerEntity |
    ParentManagerEntity | ...

然后在系统中,我希望能够断言某些属性在实体上,并让打字稿推断出,因为联合中唯一具有该属性的类型是我的系统导出的类型,那么它必须是那个导出的类型。

例如,说 CameraManager 导出

interface CameraManagerEntity {
    foo: boolean,
    bar: number
}

我的实体联合中没有其他类型有 foo 参数。我的期望是,如果我有一个实体联合的实例,则制作一个断言“foo”在实例中的 if 语句应该足以访问实例上的 bar 而不会出现类型错误。

function processEntity(entity: Entity) {
    if ("foo" in entity) {
        return entity.bar; // <-- Type error.
    }
}

我错过了什么吗?我认为在理想的世界中,编译器应该有足够的信息来知道我的实体对象是给定的 CameraManagerEntity。看来我的建议在今天存在打字稿时不起作用。有没有更好的方法来实现我想要做的事情?提前致谢。

编辑:我知道用户定义的类型保护,不必手动编写类型保护会很好,因为我认为编译器应该已经拥有所有信息。

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    您想要的几乎就像一个由内而外的Tagged Union Type。对于 Tagged Union Type,所有成员共享一个公共字段,TypeScript 通过检查该字段的值来区分(通常使用switch)。但是在您当前的设计中,联合类型的成员通过唯一字段的存在来区分。

    我想出了一个通用类型保护,它使用属性的存在来检查 entity 与类型:

    if (hasKeyOf<CameraManagerEntity>(entity, 'camera')) {
      return entity.camera;
    }
    

    这是完整的示例:

    interface CameraManagerEntity {
      camera: string;
    }
    
    interface CollisionManagerEntity {
      collision: string;
    }
    
    type Entity = CameraManagerEntity | CollisionManagerEntity;
    
    // Generic type guard 
    function hasKeyOf<T>(entity: any, key: string): entity is T {
      return key in entity;
    }
    
    function processEntity(entity: Entity) {
      if (hasKeyOf<CameraManagerEntity>(entity, 'camera')) {
        return entity.camera;
      } else if (hasKeyOf<CollisionManagerEntity>(entity, 'collision')) {
        return entity.collision;
      } 
    }
    

    Try it in TypeScript Playground

    但您可能会考虑为您的实体系统使用标记联合类型,这可能更符合人体工程学:

    interface CameraManagerEntity {
      kind: 'CameraManager';
      camera: string;
    }
    
    interface CollisionManagerEntity {
      kind: 'CollisionManager';
      collision: string;
    }
    
    type Entity = CameraManagerEntity | CollisionManagerEntity;
    
    function processEntity(entity: Entity) {
      switch (entity.kind) {
        case ('CameraManager'): return entity.camera;
        case ('CollisionManager'): return entity.collision;
      }
    }
    

    Try it in TypeScript Playground

    【讨论】:

    • 我最终做了与此非常相似的事情。我仍然相信一个足够聪明的编译器应该能够弄清楚正在使用什么类型,或者至少根据 in 运算符缩小联合中的类型,但现在编写类型保护就足够了。感谢您的回答。
    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2020-11-11
    • 1970-01-01
    • 2020-02-01
    • 2021-01-22
    • 2019-01-04
    相关资源
    最近更新 更多