Typescript有没有一种方法可以在switch语句中强制转换类型?

3

我有一个检查请求数据以访问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
    }
}

更新。


1
你想要一个用户定义的类型保护 - Jared Smith
@JaredSmith 那我应该在 if else 中链接数百个 API 端点吗? - ZiiMakc
1
初始检查开关语句很容易,但区分数据属性类型就比较困难了。我还在努力弄清楚这一部分。你可能只想使用单独的类型/类型保护。 - Jared Smith
1
你这么写会破坏类型安全。正确的做法是进行更详细的转换。 - Jared Smith
1
req as Req<End1> 不是类型转换。它被称为 类型断言,其目的是告诉编译器: “我知道我在做什么,请停止用不匹配类型的错误困扰我”。 - axiac
显示剩余7条评论
1个回答

2

根据您的使用情况,您可能会对辨别联合类型感兴趣:


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
    }
}
Playground链接

非常有趣的解决方案,甚至可以跳过“_req”部分,直接使用“Req”而不是未知。 - ZiiMakc
1
@RTW 嗯,我不知道你在 checkRole 函数中做了什么,所以我只是保留了原始的签名类型。 - Titian Cernicova-Dragomir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接