typescript - TypeScript:如何告诉 TypeScript 我是哪种情况?
问题描述
我正在使用 TypeScript 构建一个 React Native 应用程序。我的初创公司最近从 JavaScript 切换到 TypeScript,我正在迁移代码。
我有一个<FlatList />
包含两种类型的场所:餐厅和酒吧。Restaurant 和 Bar 共享一些属性,但它们也不共享。例如,该属性servesFood
是餐厅独有的。
该renderItem
函数如下所示:
renderItem = ({ item }: { item: Restaurant | Bar }) => {
return item.servesFood ? (
// ... Restaurant code
) : (
// ... Bar code
)
问题是,在这个三元运算符的条件下,TypeScript 会抛出错误:
Property 'servesFood' does not exist on type 'Restaurant | Bar'.
Property 'servesFood' does not exist on type 'Bar'
此外,在访问特定于类型的属性时,在特定于类型的代码中也存在 linting 错误。
注意:由于各种原因,我不能让他们共享一个属性并将一个设置为 true 并将另一个设置为first
true false
。
那么我如何告诉 TypeScript 在 If 子句/三元运算符项的一部分中是 Restaurant 类型,而在另一项中是 bar 类型,这样这些 linting 错误就会消失。
解决方案
您可以使用类型保护来缩小参数的类型。
您可以使用基于servesFood
字段的有区别的联合:
interface Restaurant{
servesFood: true
}
interface Bar {
servesFood?: false
}
const renderItem = ({ item }: { item: Restaurant | Bar }) => {
return item.servesFood ? (
// ... Restaurant code
) : (
// ... Bar code
)
或者,如果接口不共享servesFood
,您可以使用in
类型保护
interface Restaurant{
servesFood: true
}
interface Bar {
drinks: true
}
const renderItem = ({ item }: { item: Restaurant | Bar }) => {
return 'servesFood' in item ? (
item.servesFood
) : (
// ... Bar code
item.drinks
);
推荐阅读
- arduino - 如何将 Arduino Mega 2560 ADC 采样频率设置为 40 Hz
- php - 页面在 codeigniter 中不起作用,显示页面不起作用
- javascript - JavaScript 中的类型提示与循环引用
- spring-boot - 使用 Spring Boot Actuator 计算每秒的请求数
- ckeditor - “ckeditor”命名空间中没有定义命令
- c# - 将泛型与 GraphType 一起使用
- docker-compose - docker 容器 A 可以使用什么 URL 来访问另一个 docker 容器 B(相同的开发机器,不同的项目)
- excel - 如何使用 Excel VBA 打开 URL 列表并将每个 URL 的屏幕截图保存在我的辅助监视器上
- pandas - Pandas 查询无法识别全局环境中定义的列表
- typescript - 添加 vuex persist 插件后,我无法在路由器中存储