簡體   English   中英

TypeScript:如何告訴TypeScript我在哪?

[英]TypeScript: How to tell TypeScript in which If case I am?

我正在使用TypeScript構建一個React Native應用程序。 我的創業公司最近從JavaScript切換到TypeScript,我正在遷移代碼。

我有一個<FlatList /> ,包括兩種類型的場地:餐廳和酒吧。 餐廳和酒吧分享一些屬性,但他們也沒有。 例如,物業服務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錯誤。

注意:出於各種原因,我不能讓他們共享一個屬性,並在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
      );

您可以簡單地比較對象的鍵/值,以便了解當前項的屬性serveFood是否存在。 如果vaule是null則意味着item不包含屬性servesFood事情是這樣的:

renderItem = ({ item }: { item: Restaurant | Bar }) => {
  return ((item["servesFood"] != null) ? (
    // ... Restaurant code, it exists the property servesFood
  ) : (
    // ... Bar code, it doesn't exists the property servesFood so it is null
  ))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM