[英]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.