[英]Typescript is there a way to cast type for case in switch?
我有一個檢查請求數據以訪問 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
}
}
更新。 jared 建議的變體。
根據您的用例的具體情況,您可能對受歧視的聯合感興趣:
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.