说我有以下类型:
type MyCustomAction = {|
type: "MY_CUSTOM_ACTION",
payload: string
|}
type MyCustomAction2 = {|
type: "MY_CUSTOM_ACTION2",
data: number
|}
type CustomAction = MyCustomAction2 | MyCustomAction
const MyCustomFunction = (action: CustomAction): void => {
const type = action.type
if (type === "MY_CUSTOM_ACTION") {
let payload = action.payload
} else if (type === "MY_CUSTOM_ACTION2") {
let data = action.data
}
}
这失败了:
21: let payload = action.payload ^ Cannot get `action.payload` because property `payload` is missing in `MyCustomAction2` [1].
References:
17: const MyCustomFunction = (action: CustomAction): void => {
^ [1]
23: let data = action.data ^ Cannot get `action.data` because property `data` is missing in `MyCustomAction` [1].
References:
17: const MyCustomFunction = (action: CustomAction): void => {
^ [1]
是否可以切换这样的类型?为什么流不能检测到MyCustomAction总是有一个有效载荷?
答案 0 :(得分:0)
似乎在流编译器中是一个问题,但是如果直接使用对象字段,它会很好:)
type MyCustomAction = {|
type: "MY_CUSTOM_ACTION",
payload: string
|}
type MyCustomAction2 = {|
type: "MY_CUSTOM_ACTION2",
data: number
|}
type CustomAction = MyCustomAction2 | MyCustomAction
const MyCustomFunction = (action: CustomAction): void => {
if (action.type === 'MY_CUSTOM_ACTION') {
const payload = action.payload;
} else if (action.type === 'MY_CUSTOM_ACTION2') {
const data = action.data;
}
};