typescript - 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错误。
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:
在 < T > e 形式的类型断言表达式中,e 由 T 进行上下文类型化(第 4.23 节),并且要求 e 的结果类型可分配给 T,或者要求 T 可分配给结果类型为 e,否则会发生编译时错误。
对于案例 1,显然T
可以分配给e
。
对于情况 2, 的扩展形式e
是{bid: string, labs: Object}
, T 可分配给它。请注意,labs?
可以分配给Object
(事实上,我不确定,但这是我唯一可能的解释)。
对于情况 3,以上条件都不满足。
推荐阅读
- php - 使用 Eloquent 链接 Laravel 中的多个表
- elasticsearch - 带有过滤器的日期直方图聚合问题
- bootbox - bootbox 确认对话框,取消按钮不起作用
- c++ - 从多个 MPI 进程调用 cudaMemcpy 的最可靠方法是什么?
- scala - YARN、Kafka 上的 Flink 会话窗口缩放问题
- sql - 计算每行数据库的 Biz 天数
- php - ACF 中继器字段返回包含中继器计数的字符串
- google-bigquery - 如何在 Google BigQuery 中操作 CURRENT_DATE()?
- azure-synapse - 如何在 Azure Synapse Analytics 中执行并发流式更新插入
- javascript - 编译后 Babel 意外令牌导出