键入API响应并有条件地呈现它



我正在尝试键入API响应,并在react组件中有条件地呈现它。

我的API返回一个传递地址,该地址可以是邮政地址,属性为:type(应为"POSTAL"(、streetstreetNumber

OR具有属性的数据包地址type(应为"PACKSTATION"(packstationpostNumber

以下是我的实现:

(沙箱链接:https://codesandbox.io/s/competent-bird-dx2wp?file=/src/index.tsx:0-474(

types.ts

export enum AddressType {
packstation = "PACKSTATION",
postal = "POSTAL"
}
export interface PostalAddress {
type: AddressType.postal;
street: string;
streetNumber: string;
}
export interface PackstationAddress {
type: AddressType.packstation;
packstation: string;
postNumber: string;
}
export type DeliveryAddress = PostalAddress | PackstationAddress;

DeliveryAddressDisplay.tsx

import * as React from "react";
import { DeliveryAddress, AddressType } from "./types";

interface Props {
deliveryAddress: DeliveryAddress;
}
const DeliveryAddressDisplay = (props: Props) => {
// im trying to get the type of the address here so i don't recalculate the same thing in my JSX
const isPostalAddress: boolean = props.deliveryAddress.type === AddressType.postal;
const isPackstationAddress: boolean = props.deliveryAddress.type === AddressType.packstation;

return (
<div className="App">
<h2>
{isPostalAddress && <span>Street: {props.deliveryAddress.street}</span>}
</h2>
<h2>
{isPackstationAddress && (
<span>Packstation: {props.deliveryAddress.packstation}</span>
)}
</h2>
<h2>
{isPostalAddress && <span>Street Number: {props.deliveryAddress.streetNumber}</span>}
</h2>
<h2>
{isPackstationAddress && (
<span>Packstation: {props.deliveryAddress.postNumber}</span>
)}
</h2>
</div>
);
};
export default DeliveryAddressDisplay;

**index.js**

import * as React from "react";
import { render } from "react-dom";
import { AddressType, DeliveryAddress } from "./types";
import DeliveryAddressDisplay from "./DeliveryAddressDisplay";
// my api response for example
const johnsAddress: DeliveryAddress = {
type: AddressType.postal,
street: "John's street",
streetNumber: "17"
};
const rootElement = document.getElementById("root");
render(<DeliveryAddressDisplay deliveryAddress={johnsAddress} />, rootElement);

有了这个实现,当我试图在我的JSX中对streetstreetNumber类型进行条件渲染时,Typescript会抱怨PackstationAddress类型中不存在的类型,尽管我正在尝试渲染PostalAddress

有人能解释这种行为吗?

不太确定你得到的错误,但如果你喜欢这样做:

{props.deliveryAddress.type === AddressType.postal && <span>Street: {props.deliveryAddress.street}</span>}

则误差消失。

最新更新