首页 > 解决方案 > typescript 中类型断言的详细逻辑是什么?

问题描述

我把type assertion它当作Hi Compiler, I know the type of this variable better than you. Just follow me!.

但似乎编译器仍然有自己的逻辑来推断类型。例如,假设,

interface PM_MGEInfo {
    category: string;
    bid: string;
    cid?: string;
    labs?: { [key: string]: any };
}

那么1&2没问题,但是3抛出TS2352错误。

  1. function makeMgeInfo(bid: string): PM_MGEInfo {
        return <PM_MGEInfo>{
            bid
        };
    }
    
  2. function makeMgeInfo(bid: string): PM_MGEInfo {
        return <PM_MGEInfo>{
            bid,
            labs: {}
        };
    }
    
  3. function makeMgeInfo(bid: string): PM_MGEInfo {
        return <PM_MGEInfo>{
            bid,
            // error TS2352: Type '{ labs: { poi_id: string; }; bid: string; }' cannot be converted to type 'PM_MGEInfo'.
            // Property 'category' is missing in type '{ labs: { poi_id: string; }; bid: string; }'.
            labs: {a: 1}
        };
    }
    

为什么type assertion开始检查3中的其他字段?有人知道它的详细逻辑吗?


更新:我在 Github Microsoft/TypeScript#23698中创建了一个问题。

标签: typescripttype-assertion

解决方案


检查受此答案启发的规范4.16 Type Assertions

在 < T > e 形式的类型断言表达式中,e 由 T 进行上下文类型化(第 4.23 节),并且要求 e 的结果类型可分配给 T,或者要求 T 可分配给结果类型为 e,否则会发生编译时错误。

对于案例 1,显然T可以分配给e

对于情况 2, 的扩展形式e{bid: string, labs: Object}, T 可分配给它。请注意,labs?可以分配给Object事实上,我不确定,但这是我唯一可能的解释)。

对于情况 3,以上条件都不满足。


推荐阅读