[英]FlowType: Generic inheritance of multiple types
Imagine having two data types, both of them have an id
property: 想象一下,有两种数据类型,它们都有一个
id
属性:
type Foo = {
id: string,
// other props
}
type Bar = {
id: number,
// other props
}
Now imagine a Table
component in React which accepts an array of data as a property. 现在想象一下React中的
Table
组件,它接受数据数组作为属性。 This component needs to be generic, but we know that it requires an id
prop for every data object in the data array. 该组件必须是通用的,但是我们知道它为数据数组中的每个数据对象都需要一个
id
属性。 This id
can either be a number or a string. 此
id
可以是数字或字符串。 The props might be typed as follows: 道具的类型如下:
type Props = {
data: Array<{id: number | string}>
}
The problem is that the above notation does not work. 问题是上述表示法不起作用。 Is there a way to be able to 'retype' certain properties?
有没有一种方法可以“重新键入”某些属性?
I have looked into generic types but I can't seem to find a solution without changing the Foo
and Bar
type definitions. 我已经研究了泛型类型,但是如果不更改
Foo
和Bar
类型定义,我似乎找不到解决方案。
This is a bit too tricky for Flow to figure out I think. 我觉得Flow有点棘手。 So instead of declaring a single property that both your types share, you can declare your array as containing types
Foo | Bar
因此,不必声明两个类型都共享一个属性,而是可以将数组声明为包含
Foo | Bar
type类型Foo | Bar
Foo | Bar
. Foo | Bar
。
This is nice because it has even less repetition than your original code, and in each branch of that if statement you have free access to other unique properties of Foo
or Bar
without any issues. 这很好,因为它的重复次数甚至比原始代码少,并且在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.