TypeScript修复in类型守卫问题,实现CSS短属性转长属性类型安全转换
修复CSS简写属性转换的类型守卫问题
要解决pickedShortHandRule类型包含{}的问题,关键是让类型守卫能准确排除非目标类型,确保判断后变量类型仅为"width" | "height",具体方案如下:
第一步:定义目标类型与正确的类型守卫
首先明确简写属性的类型,并编写能精准识别它的类型守卫:
type ShortHandRule = "width" | "height"; /** * 类型守卫:判断输入是否为指定的CSS简写属性 */ function isShortHandRule(rule: {} | ShortHandRule): rule is ShortHandRule { // 先排除{}类型(typeof {}为"object"),再判断是否为目标字符串 return typeof rule === "string" && (rule === "width" || rule === "height"); }
第二步:使用类型守卫缩小类型范围
在使用pickedShortHandRule前,通过类型守卫判断,此时TypeScript会自动将变量类型缩小为"width" | "height",无需额外类型断言:
// 假设pickedShortHandRule初始类型为{} | "width" | "height" const pickedShortHandRule: {} | "width" | "height" = getShortHandRule(); if (isShortHandRule(pickedShortHandRule)) { // 此处pickedShortHandRule类型已确定为"width" | "height" const sxProps = { [pickedShortHandRule]: "100px" }; // 直接使用sxProps即可,无需as keyof SxProps }
问题根源说明
之前的类型守卫可能未明确排除{}类型:如果仅判断rule === "width" || rule === "height",当rule是{}时,该条件会返回false,但TypeScript无法自动关联这个判断与类型缩小。通过加入typeof rule === "string"的前置判断,能明确告诉TypeScript:满足条件的输入必然是字符串类型,进而缩小到目标的属性名类型。
内容的提问来源于stack exchange,提问作者glo
相关产品推荐
相关产品推荐

