简体   繁体   English

JSX 中的 TypeScript 类型断言

[英]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如果isAdmintrue 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.

See playground for working example 有关工作示例,请参见操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM