简体   繁体   中英

Why don't discriminated unions in typescript work in this way?

Why can't typescript discriminate based on a common property like this? After reading the docs I thought this would work.

Heres a typescript playground

type Mammal = { legs: number }
type Fish = { fins: number }

type Action1 = {
    type: 'a',
    payload: Mammal 
}


type Action2 = {
    type: 'b',
    payload: Fish
}

type ActionUnion = Action1 | Action2

const A: Action1 = { type: 'a', payload: { legs: 4 } }
const B: Action2 = { type: 'b', payload: { fins: 3 } }

function foo(action: ActionUnion) {
    switch (action.type) {
        case 'a':
            const { legs } = action.payload

        case 'b':
            const { fins } = action.payload

        default:
            break
    } 
}

You forgot to break your case statement. Should look like this

case 'a':
    const { legs } = action.payload
    break;
case 'b':
    const { fins } = action.payload

They do work like that, but your switch case was falling through to the next case, add a break and it will work

type Mammal = { legs: number }
type Fish = { fins: number }

type Action1 = {
    type: 'a',
    payload: Mammal 
}


type Action2 = {
    type: 'b',
    payload: Fish
}

type ActionUnion = Action1 | Action2

const A: Action1 = { type: 'a', payload: { legs: 4 } }
const B: Action2 = { type: 'b', payload: { fins: 3 } }

function foo(action: ActionUnion) {
    switch (action.type) {
        case 'a':
            const { legs } = action.payload
            break;
        case 'b':
            const { fins } = action.payload
            break;
        default:
            break
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM