给出一个由对象联合组成的数组,我试图找出一种通过Flow提取其中的两种唯一类型的方法,而不必使它们保持最新状态。
这是我的较大类型,包含两个不同对象的联合数组:
type Something = {
attachments: [
{|
// TWhatever should only match this shape
__typename: 'whatever',
uniqueToWhatever: boolean
|},
{|
__typename: 'foo',
uniqueToFoo: boolean
|}
]
}
提取联合元素类型相对简单:
type TAttachments = $PropertyType<Something, 'attachments'>;
type TAttachment = $ElementType<TAttachments, number>;
我想做的是将每种不同类型的对象提取到其自己的类型中,以便使这两个语句成为真:
// Should fail, this is not of type TWhatever
const failingCase: TWhatever = {
__typename: 'foo',
uniqueToFoo: true
}
// Should work, matches TWhatever
const successfulCase: TWhatever = {
__typename: 'whatever',
uniqueToWhatever: true
}
为此,我尝试使用$<Call>
,从the docs for $<Call>
的角度来看,我 认为这是可能的,但我还没有弄清楚。
下面是我的尝试,但是流程告诉我TWhatever的类型仍然与此处以前相同。
function whatevers(
attachments: TAttachments,
type: string
) {
return attachments.filter(a => a.__typename === type);
}
type TWhatevers = $Call<typeof whatevers, TAttachments, 'whatever'>
type TWhatever = $ElementType<TWhatevers, number>;
函数whatevers
已经在逻辑上仅返回任何类型的元素,但我认为我没有正确地指示流。
类似地,我在没有type
的{{1}}参数的情况下尝试了此操作
whatevers()
这也不完全正确。
我是在尝试将Flow和function whatevers(
attachments: TAttachments
) {
return attachments.filter(a => a.__typename === 'whatever');
}
type TWhatevers = $Call<typeof whatevers, TAttachments>
type TWhatever = $ElementType<TWhatevers, number>;
// Should fail, this is not of type TWhatever
const failingCase: TWhatever = {
__typename: 'foo',
uniqueToFoo: true
}
// Should work, matches TWhatever
const successfulCase: TWhatever = {
__typename: 'whatever',
uniqueToWhatever: true
}
推到超出其功能极限吗?还是我刚开始使用?