【发布时间】:2021-08-25 17:41:27
【问题描述】:
我要不同的界面
interface Vehicle {
// data about vehicle
}
interface Package {
// data about package
}
我有一个组件,它的 props 可以接收其中任何一个(将来可能会更多), 所以我这样创建了道具界面:
interface Props<T> {
modalVisible: boolean,
selectableData: T[],
currentlySelectedIndex: number,
onSelect: (selection: T) => void,
onBackPressed: () => void
}
在我的组件中,我有一个 FlatList 接收 selectableData 和一个 renderItem 函数,如下所示:
<FlatList
data={selectableData}
renderItem={renderItem}
style={{ maxHeight: 251 }}
ItemSeparatorComponent={() => <FlatListItemSeparator separatorStyle=
{styles.itemSeparator} />}
keyExtractor={(item, index) => index.toString()} />
const renderItem: ListRenderItem<Vehicle | Package> = ({ item }) => (
<ModalSelectionItem
topText={ item instance Vehicle ? 'a' : 'b'}
/>
);
我想根据传递的类型在FlatList 中呈现不同的文本,如何检查我的类型?我尝试同时使用 instanceof 和 typeof 但它们似乎都不起作用
【问题讨论】:
-
您不能,因为该类型信息未绑定到对象。如果要检查特定实例(使用
instanceof/typeof),则必须使用类并创建该类的实例。您可以将类型字段添加到接口结构并使用该字段来确定类型