首页 > 解决方案 > 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 并将另一个设置为firsttrue false

那么我如何告诉 TypeScript 在 If 子句/三元运算符项的一部分中是 Restaurant 类型,而在另一项中是 bar 类型,这样这些 linting 错误就会消失。

标签: typescripttypescript-typingsreact-tsxtypescript-typestypescript2.8

解决方案


您可以使用类型保护来缩小参数的类型。

您可以使用基于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
      );

推荐阅读