簡體   English   中英

為什么不區分打字稿中的聯合以這種方式工作?

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

為什么打字稿不能基於這樣的共同屬性進行區分? 閱讀文檔后,我認為這會起作用。

這是打字稿游樂場

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

你忘了打破你的案情陳述。 應該看起來像這樣

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

它們確實可以那樣工作,但是您的開關盒陷入了下一個情況,請添加一個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