【发布时间】:2018-11-16 05:16:29
【问题描述】:
我正在为具有不同参数对的通用函数的流类型声明而苦苦挣扎。
我的目标是有一个函数,它根据输入参数返回某个联合类型的对象。 我有大量要输入的消息(在这个例子中我只使用了两个)
type Message1 = {
event: 'UI',
type: 'receive',
payload: boolean
}
type Message2 ={
event: 'UI',
type: 'send',
payload: {
foo: boolean;
bar: string;
}
}
type MessageFactory<T> = (type: $PropertyType<T, 'type'>, payload: $PropertyType<T, 'payload'>) => T;
export const factory: MessageFactory<Message1> = (type, payload) => {
return {
event: 'UI',
type,
payload
}
}
factory('receive', true);
// factory('send', { foo: true, bar: "bar" });
当我改变时
MessageFactory<Message1>
到
MessageFactory<Message1 | Message2>
会报错
Could not decide which case to select. Since case 1 [1] may work but if it doesn't case 2 [2] looks promising too. To fix add a type annotation to `payload` [3] or to `type` [4]
你可以联系它here
知道如何声明这个函数吗?
或者这是愚蠢的想法,我走错了方向?
有更好的解决方案吗?
【问题讨论】:
标签: flowtype