您只需要一个将枚举值映射到输入/响应类型的查找类型。例如:
enum ApiOperations {
A,
B,
}
interface ApiOperationsLookup {
[ApiOperations.A]: {
input: { a: number }
response: { a: string }
}
[ApiOperations.B]: {
input: { b: number }
response: { b: string }
}
}
在这里
ApiOperationsLookup
是具有
ApiOperations
映射到特定的输入和响应类型。
您可以通过以下方式获取输入类型:
type Test = ApiOperationsLookup[ApiOperations.A]['input']
// { a: number }
现在你可以
callApi
如下所示:
async callApi<T extends ApiOperations>(
op: T,
input: ApiOperationsLookup[T]['input'],
functionName: string
): Promise<ApiOperationsLookup[T]['response']> {
//...
}
这里是泛型参数
T
是来自
API运营
,然后
input
并从该操作的查找映射中提取返回类型。
现在,我想你已经预料到了:
const aResponse = await instance.callApi(ApiOperations.A, { a: 123 }, 'aFuncName')
// { a: string }
const aBadResponse = await instance.callApi(ApiOperations.A, { b: 123 }, 'aFuncName')
// type error on second argument
const bResponse = await instance.callApi(ApiOperations.B, { b: 123 }, 'aFuncName')
// { b: string }
Playground
另一个选项是跳过查找类型,而是在为枚举的每个成员创建函数签名时使用重载:
// signature for each enum member
async callApi(op: ApiOperations.A, input: { a: number }, functionName: string): Promise<{ a: string }>
async callApi(op: ApiOperations.B, input: { b: number }, functionName: string): Promise<{ b: string }>
// implementation
async callApi(
op: ApiOperations,
input: unknown,
functionName: string
): Promise<unknown> {
//...
}
我认为这是一个更丑陋,更难维护个人,但这是一个意见的问题。
Playground