91 lines
2.1 KiB
Markdown
91 lines
2.1 KiB
Markdown
# UTS Android executeAs 类型优化总结
|
||
|
||
## 优化背景
|
||
UTS Android 对 `executeAs<T>()` 的类型处理有特殊要求:
|
||
1. 需要定义具体的 type,不能使用内联类型
|
||
2. 不需要传 `Array<T>`,返回时会自动转换成 `Array<T>`
|
||
|
||
## 优化前
|
||
```typescript
|
||
// 错误的方式 - 使用内联类型和显式 Array
|
||
.executeAs<Array<{
|
||
id: string
|
||
status: string
|
||
}>>()
|
||
```
|
||
|
||
## 优化后
|
||
```typescript
|
||
// 正确的方式 - 定义具体类型,不传 Array
|
||
type AssignmentData = {
|
||
id: string
|
||
status: string
|
||
}
|
||
|
||
.executeAs<AssignmentData>()
|
||
```
|
||
|
||
## 具体修改
|
||
|
||
### 1. 新增类型定义
|
||
```typescript
|
||
// 作业数据类型
|
||
type AssignmentData = {
|
||
id: string
|
||
status: string
|
||
}
|
||
|
||
// 用户数据类型
|
||
type UserData = {
|
||
id: string
|
||
}
|
||
|
||
// 作业活动数据类型
|
||
type AssignmentActivityData = {
|
||
id: string
|
||
title: string | null
|
||
description: string | null
|
||
status: string | null
|
||
created_at: string
|
||
updated_at: string
|
||
}
|
||
```
|
||
|
||
### 2. 修改 executeAs 调用
|
||
```typescript
|
||
// 作业统计查询
|
||
.executeAs<AssignmentData>() // 不再使用 Array<AssignmentData>
|
||
|
||
// 用户统计查询
|
||
.executeAs<UserData>() // 不再使用 Array<UserData>
|
||
|
||
// 活动查询
|
||
.executeAs<AssignmentActivityData>() // 不再使用 Array<AssignmentActivityData>
|
||
```
|
||
|
||
## 优化效果
|
||
|
||
### 1. 类型安全
|
||
- 编译时类型检查更加严格
|
||
- 避免 UTS Android 的类型推断问题
|
||
- 确保数据结构的一致性
|
||
|
||
### 2. 代码简洁
|
||
- 移除冗长的内联类型定义
|
||
- 类型定义可复用
|
||
- 提高代码可读性
|
||
|
||
### 3. 平台兼容
|
||
- 符合 UTS Android 的类型系统要求
|
||
- 自动数组转换减少手动处理
|
||
- 避免编译错误
|
||
|
||
## 最佳实践
|
||
|
||
1. **类型定义优先**: 先定义清晰的 type,再使用 executeAs
|
||
2. **避免内联类型**: 不在 executeAs 中使用复杂的内联类型
|
||
3. **信任自动转换**: 让 UTS Android 自动处理 Array 转换
|
||
4. **保持一致性**: 所有数据查询都使用相同的模式
|
||
|
||
这次优化完全符合 UTS Android 的最佳实践,确保类型安全的同时提高了代码质量。
|