[英]TypeScript Type Assertion in JSX
如何斷言配置文件是僅在isAdmin
JSX 區域內的 UserProfileForAdmin 類型,以僅顯示管理員的電話號碼。
import { View, Text } from "react-native";
interface Profile {
name: string;
}
interface UserProfileForAdmin extends Profile {
phone: string;
}
export interface HomeSingleProfileProps {
profile: Profile | UserProfileForAdmin;
isAdmin: boolean;
}
const SingleProfile = (props: HomeSingleProfileProps) => {
return (
<View>
<Text>
{props.isAdmin ? (
<>
{props.profile.phone}
</>
) : (
<>
{props.profile.name}
</>
)}
</Text>
</View>
);
};
export default SingleProfile;
目前它給出了錯誤
TS2339:“配置文件 | 類型”上不存在屬性“電話” UserProfileForAdmin'。 “配置文件”類型上不存在屬性“電話”。
似乎這種類型是錯誤的:
export interface HomeSingleProfileProps {
profile: Profile | UserProfileForAdmin;
isAdmin: boolean;
}
根據該類型, isAdmin
可能是true
,並且profile
可能具有沒有phone
的類型。
所以我猜你想要的是一個profile
只能是UserProfileForAdmin
如果isAdmin
是true
。 如果是這樣,那么您需要在您的類型中顯示這一點。
interface UserProfileProps {
profile: Profile;
isAdmin: false;
}
export interface AdminProfileProps {
profile: UserProfileForAdmin;
isAdmin: true;
}
export type HomeSingleProfileProps = UserProfileProps | AdminProfileProps
HomeSingleProfileProps
現在是兩種可能性之一。 它要么是 admin 的 admin 配置文件和phone
,要么它不是 admin 並且它的配置文件沒有 `phone.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.