我有一个检查请求数据以访问api端点的函数。对于每个端点,此特定端点可以有不同的预加载数据。
问题在于,对于每个操作,我都需要将请求数据转换为端点数据类型。有没有一种方法可以只对case块范围断言一次?或者我应该采取一些不同的方法。
操场。
type Req<T = unknown> = { endpoint: string, data: T}
type End1 = string
type End2_3 = number
const checkRole = (req: unknown): boolean => {
switch ((req as Req).endpoint) {
case 'endpont1': {
if((req as Req<End1>).data = 'hi') return true
}
case 'endpont2':
case 'endpont3': {
(req as Req<End2_3>).data += 1;
(req as Req<End2_3>).data *= 1;
(req as Req<End2_3>).data -= 1;
if((req as Req<End2_3>).data = 5) return true
}
default: return false
}
}
UPD。罐头建议的变体。
依靠您的用例的细节,您可能对有区别的联合感兴趣:
type Req = { endpoint: "endpoint1", data: string }
| { endpoint: "endpoint3" | "endpoint2", data: number }
const checkRole = (_req: unknown): boolean => {
let req = _req as Req;
switch (req.endpoint) {
case 'endpoint1': {
if (req.data = 'hi') return true
return false;
}
case 'endpoint3':
case 'endpoint2': {
req.data += 1;
req.data *= 1;
req.data -= 1;
if (req.data == 5) return true
}
default: return false
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句