簡體   English   中英

注釋可以返回兩種不同類型對象的函數的正確方法是什么?

[英]What is the proper way to annotate a function that can return two different types of objects?

我想知道如何注釋一個可以返回兩個不同對象的函數。 例如,許多庫將使用類似於以下的模式:

// @flow
type MaybeResult = {| err: string |} | {| favoriteFruit: void |};

const getFavoriteFruitObj = (name): MaybeResult => 
  name === 'john' ? ({ favoriteFruit: 'apple' }) : ({ err: 'I only know peter\'s favorite fruit!' });

但是,這從流返回以下錯誤:

5:   name === 'john' ? ({ favoriteFruit: 'apple' }) : ({ err: 'I only know peter\'s favorite fruit!' });
                                         ^ Cannot return `name === 'john' ? {...} : {...}` because string [1] is incompatible with undefined [2] in property `favoriteFruit`.
References:
5:   name === 'john' ? ({ favoriteFruit: 'apple' }) : ({ err: 'I only know peter\'s favorite fruit!' });
                                         ^ [1]
2: type MaybeResult = {| err: string |} | {| favoriteFruit: void |};
                                                            ^ [2]

對此進行注釋的正確方法是什么?

使用| 是創建Union的正確方法,即表示可能會返回不同類型集的值的方法。

報告錯誤流的原因是因為favoriteFruit已用voidundefined )進行了注釋,但是您隨后從該函數返回了一個具有string類型的屬性的值。

也許應該是Maybe類型? 可能是這樣。 將其更改為?string typechecks正確。

暫無
暫無

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

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