【发布时间】:2021-02-15 17:50:47
【问题描述】:
我正在尝试强制键入后端处理,但在泛型如何与 ...args 交互时遇到问题。
以下是带有声明和 2 个用例的代码示例。案例之间的唯一区别是在第一种情况下明确设置了配置类型。
问题
- 在第一种情况下 - 配置输入良好,但实例输入缺乏。
- 在第二种情况下 - 配置输入缺少,但实例输入良好。
理想情况下,我希望 良好 输入配置和服务。
我尝试了Parameters<typeof someFunction>,它可以正常工作,只有泛型有时会失败。
检查TS playground,以便您了解它是如何工作的(您可以将鼠标悬停以检查类型等)。 TS 版本为4.1.3。
提前感谢您的帮助。
/************** DECLARATION ******************/
interface EndpointConfig {
in: (...args: any) => void
out: (value: 'correct') => void
}
type EndpointConfigs = Record<string, EndpointConfig>
class ApiService<ENDPOINT_CONFIGS extends EndpointConfigs> {
constructor( public endpointConfigs: ENDPOINT_CONFIGS ) {}
endpoint <ENDPOINT extends keyof ENDPOINT_CONFIGS>(endpoint: ENDPOINT): ApiEndpoint<ENDPOINT_CONFIGS, ENDPOINT> {
return new ApiEndpoint( endpoint )
}
}
class ApiEndpoint<ENDPOINT_CONFIGS extends EndpointConfigs, ENDPOINT extends keyof ENDPOINT_CONFIGS> {
constructor( public endpoint: ENDPOINT ) {}
async run (...args: Parameters<ENDPOINT_CONFIGS[ENDPOINT]['in']>): Promise<any> {}
}
/************** CASE 1 *******************/
const endpointConfigs1: EndpointConfigs = {
testEndpoint: {
in: (value: 'correct') => {},
out: (value) => { value++ } // <- Complains here. Which is correct.
}
};
const apiServiceInstance1 = new ApiService(endpointConfigs1)
const testEndpoint1 = apiServiceInstance1.endpoint('testEndpoint')
testEndpoint1.run('wrong') // <- Doesn't complain here. Which is NOT what we want.
/************** CASE 2 *******************/
const endpointConfigs2 = {
testEndpoint: {
in: (value: 'correct') => 'wrong',
out: (value) => { value++ } // <- value is considered `any` here. Which is NOT what we want.
}
};
const apiServiceInstance2 = new ApiService(endpointConfigs2)
const testEndpoint2 = apiServiceInstance2.endpoint('testEndpoint')
testEndpoint2.run('wrong') // <- Complains here, which is what we want.
【问题讨论】:
标签: typescript typescript-typings