【发布时间】:2021-12-29 22:06:32
【问题描述】:
我如何断言配置文件是仅在 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'。 “配置文件”类型上不存在属性“电话”。
编辑: 有没有办法从下面的代码中断言类型?
import { View, Text } from "react-native";
interface Profile {
name: string;
}
interface UserProfileForAdmin extends Profile {
phone: string;
}
export interface HomeSingleProfileProps {
profile: Profile | UserProfileForAdmin;
}
const SingleProfile = (props: HomeSingleProfileProps) => {
// logic to determine if the current user is admin or not
const isAdmin = checkIfUserIsAdmin(user); // might be true or false
return (
<View>
<Text>
{props.isAdmin ? (
<>
{props.profile.phone}
</>
) : (
<>
{props.profile.name}
</>
)}
</Text>
</View>
);
};
export default SingleProfile;
【问题讨论】:
标签: reactjs typescript react-native jsx