我将 type assertion
视为类似 编译器,您好,我比您更了解此变量的类型。跟我来!
。
不过好像编译器还是有自己的逻辑来推断类型的。例如,假设,
interface PM_MGEInfo {
category: string;
bid: string;
cid?: string;
labs?: { [key: string]: any };
}
然后,1&2没问题,但是3抛出TS2352错误。
-
function makeMgeInfo(bid: string): PM_MGEInfo { return <PM_MGEInfo>{ bid }; }
-
function makeMgeInfo(bid: string): PM_MGEInfo { return <PM_MGEInfo>{ bid, labs: {} }; }
-
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/