前言
interface是 ArkTS 中定义对象结构的语法。在「猫猫大作战」中,interface 用于定义猫咪数据结构、游戏配置、API 响应格式等。
一、interface 基础
exportinterfaceCat{id:string;level:CatLevel;x:number;y:number;falling:boolean;}exportinterfaceComboInfo{count:number;multiplier:number;lastMergeTime:number;}exportinterfaceCatConfigItem{name:string;emoji:string;score:number;size:number;color:string;}二、interface 使用
// 函数参数类型化functioncalculateScore(cat:Cat,combo:ComboInfo):number{returnCatConfig[cat.level].score*combo.multiplier;}// 数组类型化functionprocessCats(cats:Cat[]):Cat[]{returncats.filter(c=>c.falling);}// 嵌套接口exportinterfaceGameSnapshot{score:number;cats:Cat[];combo:ComboInfo;gameTime:number;}三、interface vs type
| 特性 | interface | type |
|---|---|---|
| 扩展性 | ✅ 可合并 | ❌ 不可合并 |
| 联合类型 | ❌ | ✅ `type A = B |
| 性能 | 相同 | 相同 |
| 推荐场景 | 对象结构 | 联合/工具类型 |
四、游戏中的应用
// API 响应接口exportinterfaceApiResponse<T>{code:number;message:string;data:T;}exportinterfaceLeaderboardEntry{rank:number;playerName:string;score:number;gameDate:string;}// 使用asyncfunctiongetLeaderboard():Promise<ApiResponse<LeaderboardEntry[]>>{// ...}五、最佳实践
- 对象结构用 interface:Cat、ComboInfo 等
- 联合类型用 type:
type Level = 1 | 2 | 3 - 前缀统一:接口名以名词为主
- 导出接口:
export interface供其他模块使用
总结
interface 定义对象的结构类型,在游戏中用于猫咪、得分、API 响应等数据结构。核心要点:interface Cat { ... }定义结构、Cat[]数组类型、export跨模块共享。
如果这篇文章对你有帮助,欢迎点赞👍、收藏⭐、关注🔔,你的支持是我持续创作的动力!
相关资源:
- ArkTS interface 文档
- 第 115 篇:record-config
- 第 117 篇:strict-type
- 第 118 篇:constructor