簡體   English   中英

Typescript/React - 一種道具的多種類型不起作用

[英]Typescript/React - Multiple types for one prop not working

我定義了以下類型。 CurrencyStatScoreStat擴展了Stat

export interface Stat {
  value: number;
  change?: number;
}

type Currency = "USD" | "RMB";

export interface CurrencyStat extends Stat {
  currency: Currency;
}

export interface ScoreStat extends Stat {
 outof: number;
}

現在我正在嘗試定義一個組件StatDisplay ,以顯示統計信息,而不管它是哪種統計類型。 我收到以下錯誤: Property 'currency' does not exist on type 'Stat | CurrencyStat'. Property 'currency' does not exist on type 'Stat'.ts(2339) Property 'currency' does not exist on type 'Stat | CurrencyStat'. Property 'currency' does not exist on type 'Stat'.ts(2339) Property 'currency' does not exist on type 'Stat | CurrencyStat'. Property 'currency' does not exist on type 'Stat'.ts(2339) ,即使我在 prop stat上使用聯合類型。

我是這些[reading typescript docs][1]說“如果我們有一個聯合類型的值,我們只能訪問聯合中所有類型共有的成員。” 這就解釋了為什么聯合類型在這里可能不起作用,但現在我很難找到一種方法來使它起作用。

我知道可以刪除CurrencyStat並將currency添加為Stat的可選屬性,但稍后會有更多的統計類型,如果可能的話,我希望將它們分開。

import { CurrencyStat, ScoreStat, Stat } from "../../../../types/types";
export const StatDisplay = ({
  label,
  stat,
}: {
  label: string;
  stat: Stat | CurrencyStat;
}) => {
  return (
    <div className="flex flex-col items-center">
      <div className="flex items-center">
        <div className="">{stat?.currency}</div>
        <div className="text-2xl font-semibold">{stat.value}</div>
      </div>
      <div className="">{label}</div>
    </div>
  );
};

CurrencyStat已經實現了Stat接口,因為您正在使用它進行擴展。

要解決您的問題,您只需將組件 function params stat變量更改為CurrenyStatStat & Partial<CurrencyStat>

Partial意味着您可以使用Stat鍵傳遞 object 但不能保證CurrencyStat

這是示例:

export const StatDisplay = ({
  label,
  stat,
}: {
  label: string;
  stat: Stat & Partial<CurrencyStat>;
}) => { ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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