ZiiMakc
ZiiMakc

Reputation: 36946

Typescript is there a way to cast type for case in switch?

I have a function that check request data to access api endpoint. For each endpoint there can be different preLoaded data for this specific endpoint.

Problem is that for every operation i need to cast request data to endpoint data type. Is there a way to assert it only one time for case block scope? Or i should take some different approach.

Playground.

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. Variant that jared suggested.

Upvotes: 4

Views: 2185

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250036

Depeding on the specifics of your use case, you might be interested in discriminated unions:


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 Link

Upvotes: 2

Related Questions