强类型 Getter 机制通过私有异步字段+只读 getter 封装最终状态,对外提供安全、明确、不可篡改的只读视图;支持 readonly 类型强化、计算型属性抽象、状态类型守卫,确保调用方获得类型严谨且无副作用的数据访问接口。
强类型 getter 机制本身不直接处理异步逻辑,但它能为异步 sdk 构建一层**安全、明确、不可篡改的只读视图**。关键不是让 getter 变成 async,而是用它封装异步结果的“最终状态”,把可变性控制在内部,对外暴露稳定、类型严谨的只读接口。
用私有异步字段 + 只读 Getter 封装状态
把异步获取的数据存在私有字段(如 private _data: T | null = null),配合一个非 async 的 getter返回当前快照:
- Getter 不触发新请求,只做安全读取:get data(): T | undefined { return this._data ?? undefined; }
- 外部无法赋值,也无法绕过校验修改原始字段
- 类型系统确保调用方拿到的是明确的 T | undefined,而非 any 或隐式 any
搭配 readonly 类型或只读类强化语义
在 TypeScript 或 PHP 8.3+ 中,进一步收窄权限:
- TypeScript:用 readonly data: T 字段(需构造时赋值)+ getter 组合,或直接声明 get data(): Readonly
- PHP 8.3:将响应数据结构定义为 readonly class ApiResponse,再通过 getter 返回该只读实例
- 效果是:即使内部缓存被更新,外部拿到的对象本身也是冻结的,无法意外 mutate
用 getter 暴露计算型只读属性,而非原始数据
避免直接暴露 raw response,转而提供业务语义清晰的只读字段:
- get isConnected(): boolean { return this._status === 'connected'; }
- get lastUpdatedAt(): Date | null { return this._lastUpdate ? new Date(this._lastUpdate) : null; }
- get isReady(): boolean { return !!this._data && this._status === 'success'; }
- 所有这些 getter 都不改变内部状态,也不触发副作用,但对外统一了判断逻辑
配合 loading/error 状态做类型守卫
只读窗口的价值不仅在于“数据”,更在于“状态上下文”。用 getter 封装类型断言能力:
- get dataOrThrow(): T { if (!this._data) throw new Error('Data not loaded'); return this._data; }
- get hasError(): boolean { return this._error !== null; }
- get error(): Error | null { return this._error; }
- 这样调用方可基于 getter 结果做类型缩小(TypeScript),或安全分支处理(PHP 8.3 union types + match)

















