簡體   English   中英

JSX 中的 TypeScript 類型斷言

[英]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如果isAdmintrue 如果是這樣,那么您需要在您的類型中顯示這一點。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM