[英]FlowType: Generic inheritance of multiple types
想象一下,有两种数据类型,它们都有一个id
属性:
type Foo = {
id: string,
// other props
}
type Bar = {
id: number,
// other props
}
现在想象一下React中的Table
组件,它接受数据数组作为属性。 该组件必须是通用的,但是我们知道它为数据数组中的每个数据对象都需要一个id
属性。 此id
可以是数字或字符串。 道具的类型如下:
type Props = {
data: Array<{id: number | string}>
}
问题是上述表示法不起作用。 有没有一种方法可以“重新键入”某些属性?
我已经研究了泛型类型,但是如果不更改Foo
和Bar
类型定义,我似乎找不到解决方案。
我觉得Flow有点棘手。 因此,不必声明两个类型都共享一个属性,而是可以将数组声明为包含Foo | Bar
type类型Foo | Bar
Foo | Bar
。
这很好,因为它的重复次数甚至比原始代码少,并且在if语句的每个分支中,您都可以自由访问Foo
或Bar
其他唯一属性,而不会出现任何问题。
// @flow
type Foo = {
id: string,
// other props
}
type Bar = {
id: number,
// other props
}
type Props = {
data: Array<Foo | Bar>
}
const foo: Foo = { id: 'A' }
const bar: Bar = { id: 1 }
const props: Props = { data: [foo, bar] }
for (const item of props.data) {
if (typeof item.id === 'string') {
console.log('I am a Foo')
} else {
console.log('I am a Bar')
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.