我有多个服务,它们都返回相同的结果:
type result = {
success: boolean
data?: any
}
const a = async (): Promise<result> => {
...
}
const b = async (): Promise<result> => {
...
}
但a
的数据与b
不同:
const a = async (): Promise<result> => {
return {
success: true,
data: { x: 1 }
}
}
const b = async (): Promise<result> => {
return {
success: true,
data: { y: 1 }
}
}
我只想改变每个
的数据类型data: { x: 1 } as anotherTypeX
data: { x: 1 } as anotherTypeY
使用泛型将为您解决这个问题,并且您将获得适当的键入支持。
查看这里的文档
type result<T> = {
success: boolean;
data?: T;
}
type A = {
x: number;
}
type B = {
y: number;
}
const a = async (): Promise<result<A>> => {
return {
success: true,
data: { x: 1 }
}
}
const b = async (): Promise<result<B>> => {
return {
success: true,
data: { y: 1 }
}
}