![](/img/trans.png)
[英]proper way to override function with different param types in TypeScript
[英]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
已用void
( undefined
)進行了注釋,但是您隨后從該函數返回了一個具有string
類型的屬性的值。
也許應該是Maybe
類型? 可能是這樣。 將其更改為?string
typechecks正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.