typescript - typescript 中类型断言的详细逻辑是什么?

标签 typescript type-assertion

我将 type assertion 视为类似 编译器,您好,我比您更了解此变量的类型。跟我来!

不过好像编译器还是有自己的逻辑来推断类型的。例如,假设,

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 .

最佳答案

检查规范 4.16 Type Assertions ,灵感来自 this answer :

In a type assertion expression of the form < T > e, e is contextually typed (section 4.23) by T and the resulting type of e is required to be assignable to T, or T is required to be assignable to the widened form of the resulting type of e, or otherwise a compile-time error occurs.

对于情况 1,T 显然可以分配给 e

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

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

关于typescript - typescript 中类型断言的详细逻辑是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50015151/

相关文章:

Angular如何使用combineLatest组合来自网站网址栏的路线和查询

go - 使用接受 io.Writer 作为 HandleFunc 的函数

go - 从接口(interface)转换为实际对象时出现类型断言错误

angular - 获取状态码 http.get response angular2

node.js - 如何在没有类型定义的情况下在 Typescript 中导入 Node 模块?

reactjs - 具有通用初始类型的高阶组件

javascript - 检查指针是否与 OpenLayers 中的集群子特征相交?

go - 键入断言嵌套接口(interface)

arrays - Golang 将 interface{} 转换为 N 大小的数组

slice 指针的 Golang 类型断言