TypeScript自定义返回类型:为不同服务指定不同data类型
解决方案
把原本的result类型改成泛型类型,就能为每个服务单独指定data的类型,同时保持返回结构的一致性:
1. 定义泛型结果类型
将result改为接受泛型参数的类型,默认值设为unknown(比any更安全):
type Result<T = unknown> = { success: boolean data?: T }
2. 声明各服务的Data类型
提前定义每个服务对应的data结构类型:
// 服务a的data类型 type AnotherTypeX = { x: number } // 服务b的data类型 type AnotherTypeY = { y: number }
3. 为服务指定泛型参数
在声明服务的返回类型时,传入对应的泛型参数,TypeScript会自动校验data的结构:
const a = async (): Promise<Result<AnotherTypeX>> => { return { success: true, data: { x: 1 } // 自动匹配AnotherTypeX,无需额外断言 } } const b = async (): Promise<Result<AnotherTypeY>> => { return { success: true, data: { y: 1 } } }
如果确实需要显式使用as断言(比如后端返回数据需要强制类型转换),也可以这样写:
const a = async (): Promise<Result<AnotherTypeX>> => { return { success: true, data: { x: 1 } as AnotherTypeX } }
这种方式既保留了统一的返回结构,又能让每个服务的data拥有独立的类型约束,避免any带来的类型不安全问题,同时在调用服务时能获得准确的类型提示。
内容的提问来源于stack exchange,提问作者MHHH
相关产品推荐
相关产品推荐

