p***@gmail.com
p***@gmail.com
  • 发布:2025-12-29 16:08
  • 更新:2025-12-29 16:09
  • 阅读:24

UTS 插件对安卓数组转为 UTSArray 后使用 some 方法报错

分类:uts

index.uts 文件代码示例:

const shortcutManager = context.getSystemService(android.content.Context.SHORTCUT_SERVICE) as android.content.pm.ShortcutManager;  

const arr = Array.fromNative(shortcutManager.getPinnedShortcuts());  

if (arr.some((e: ShortcutInfo) => e.getId() === 'id')) {  
}

会在控制台报错:

15:59:10.796 ‌error: None of the following functions can be called with the arguments supplied: ‌
15:59:10.799 ‌public open fun some(callback: (value: ShortcutInfo!) -> Boolean): Boolean defined in io.dcloud.uts.UTSArray‌
15:59:10.799 ‌public open fun some(callback: (value: ShortcutInfo!, index: Number) -> Boolean): Boolean defined in io.dcloud.uts.UTSArray‌
15:59:10.803 ‌public open fun some(callback: (value: ShortcutInfo!, index: Number, array: UTSArray<ShortcutInfo!>) -> Boolean): Boolean defined in io.dcloud.uts.UTSArray‌

‌error: 类型不匹配: 推断类型是Boolean,但预期的是Unit。

本意是将安卓的 List<ShortcutInfo> 数据类型转为 UTSArray<ShortcutInfo> 再使用 some 语法来判断数组中是否存在满足条件的项, 主要是不想写 UTSArray forEach, 而且好像也不支持 kt 的 any 语法 (直接对getPinnedShortcuts() 结果进行调用)

2025-12-29 16:08 负责人:无 分享
已邀请:
Ask小助手

Ask小助手 - Ask社区AI助手

该问题请在专业群( uni-app 官方技术交流群 1 ) 咨询,群中有相关专业的管理员和群友。

根据问题描述和知识库内容,UTSArray 的 some 方法签名与标准 JavaScript 有所不同。错误提示表明回调函数参数不匹配,UTSArray 的 some 方法要求回调函数必须包含索引参数。

解决方案:

  1. 修改回调函数,添加索引参数:

    if (arr.some((e: ShortcutInfo, index: number) => e.getId() === 'id')) {  
    }
  2. 或使用完整参数形式:

    if (arr.some((e: ShortcutInfo, index: number, array: UTSArray<ShortcutInfo>) => {  
    return e.getId() === 'id';  
    })) {  
    }

原因分析:

  • 根据知识库文档 uts-for-android > 2.3 数据类型差异,UTS 对 Android 平台数据类型做了适配,但部分 API 需要严格匹配参数类型
  • UTSArray 的 some 方法重载要求必须包含索引参数(参考错误信息中的第二个重载版本)
  • 错误"推断类型是Boolean,但预期的是Unit"表明 TypeScript 编译器对回调函数返回类型推断异常

替代方案:
若仍需使用类似 some 的功能,可考虑:

let exists = false;  
arr.forEach(e => {  
    if (e.getId() === 'id') exists = true;  
});  
if (exists) { /*...*/ }

建议查阅 UTSArray 文档 了解 UTS 数组类型的具体行为。当前 uni-app X 正式版 4.87 中 UTSArray 实现可能与标准 JS 数组存在差异。

内容为 AI 生成,仅供参考

要回复问题请先登录注册