简体   繁体   English

为什么不区分打字稿中的联合以这种方式工作?

[英]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 它们确实可以那样工作,但是您的开关盒陷入了下一个情况,请添加一个break ,这样就可以了

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
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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