我有一个全局类型如下:
declare global {
type ResponseData = {
opcode: number;
message: string;
data?: <WILL-CHANGE-ON-EACH-CASE>;
};
}
我想在每个特定返回的data
字段上放置一个自定义类型。例如:
interface AppInformation {
NAME: string;
VERSION: string;
}
// What should I put on a return type???
export const getAppInfo = (): {...ResponseData, data: AppInformation } => {
return apiResponse.success(200, CONFIG.APP);
};
我应该在返回类型getAppInfo
上放什么?我留下一些东西,让我知道我在找什么。
谢谢之前,
您希望ResponseData
是一个泛型类型,具有代表data
属性类型的类型参数(例如)T
:
type ResponseData<T> = {
opcode: number;
message: string;
data?: T
};
然后你可以在需要的时候指定T
,以"插入"。特定类型,如AppInformation
:
interface AppInformation {
NAME: string;
VERSION: string;
}
const getAppInfo = (): ResponseData<AppInformation> => {
return {
opcode: 1, message: "msg", data: {
NAME: "name", VERSION: "ver"
}
}
};
编译器会理解data
(如果存在)的类型是AppInformation
:
console.log(getAppInfo().data?.NAME.toUpperCase())
Playground链接到代码