[英]How can I tell TypeScript that I am handling the case where an string is used to access an inexistent property on an object?
[英]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.