如何在TypeScript中判断Kotlin后端返回的ErrorDto实例是否匹配
问题解决:TypeScript中匹配Kotlin数据类实例的判断逻辑
问题背景
后端用Kotlin定义的数据类:
data class UpdateExample( val failures: List<ErrorDto> = emptyList() ) data class ErrorDto(val errorCode: String)
前端通过TypeScript Hook获取实例后,尝试编写如下判断语句时触发类型不匹配报错:
if(updateExample?.data?.failures[0] === "ruleError") return true
报错信息:This condition will always return 'false' since the types '{ errorCode: string; }' and 'string' have no overlap
需要实现类似Kotlin中if(updateExample?.data?.failures[0] === ErrorDto("ruleError")) return true的判断逻辑。
解决方法
Kotlin的data class会自动生成基于属性值的equals方法,但TypeScript中对象用===比较的是引用而非属性值,因此需要调整判断逻辑:
方法1:直接校验属性值
这是最直接的写法,和Kotlin的判断逻辑完全等效:
if(updateExample?.data?.failures[0]?.errorCode === "ruleError") return true
通过可选链?.避免空值报错,直接对比目标对象的errorCode属性。
方法2:封装复用判断函数
如果需要多次进行这类判断,可以封装函数模拟Kotlin data class的相等性校验:
function matchesErrorDto(error: ErrorDto | undefined | null, targetCode: string): boolean { return error?.errorCode === targetCode } // 使用示例 if(matchesErrorDto(updateExample?.data?.failures[0], "ruleError")) return true
关键注意点
- 必须使用可选链
?.,防止updateExample、data为空,或failures是 emptyList 时触发读取未定义属性的错误。 - TypeScript中对象
===是引用比较,只有两个对象指向同一内存地址时才会返回true,因此不能直接用对象和字符串、新创建的对象做对比。
内容的提问来源于stack exchange,提问作者inconnu
相关产品推荐
相关产品推荐

