[英]TypeScript Type Assertion in JSX
How can I assert that the profile is UserProfileForAdmin type only inside the isAdmin
JSX area to display the phone number only for the admins.如何断言配置文件是仅在
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;
Currently it gives the error目前它给出了错误
TS2339: Property 'phone' does not exist on type 'Profile |
TS2339:“配置文件 | 类型”上不存在属性“电话” UserProfileForAdmin'.
UserProfileForAdmin'。 Property 'phone' does not exist on type 'Profile'.
“配置文件”类型上不存在属性“电话”。
It seems like this type is wrong:似乎这种类型是错误的:
export interface HomeSingleProfileProps {
profile: Profile | UserProfileForAdmin;
isAdmin: boolean;
}
According to that type, isAdmin
could be true
, and profile
could have a type that does not have a phone
.根据该类型,
isAdmin
可能是true
,并且profile
可能具有没有phone
的类型。
So I'm guessing that what you want is that a profile
can only can a UserProfileForAdmin
if isAdmin
is true
.所以我猜你想要的是一个
profile
只能是UserProfileForAdmin
如果isAdmin
是true
。 If so, then you need to show that in your types.如果是这样,那么您需要在您的类型中显示这一点。
interface UserProfileProps {
profile: Profile;
isAdmin: false;
}
export interface AdminProfileProps {
profile: UserProfileForAdmin;
isAdmin: true;
}
export type HomeSingleProfileProps = UserProfileProps | AdminProfileProps
Here HomeSingleProfileProps
is now one of two possibilities. HomeSingleProfileProps
现在是两种可能性之一。 It's either an an admin with an admin profile with a phone
, or it's not an admin and it has a profile without a `phone.它要么是 admin 的 admin 配置文件和
phone
,要么它不是 admin 并且它的配置文件没有 `phone.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.