簡體   English   中英

TypeScript 帶有 if 語句的 DeepMap 聯合類型

[英]TypeScript DeepMap Union type with if statement

我正在嘗試使用可選字段的結構創建一個 Union 類型。 我創建了以下類型:

export type StartEndType = {
  start_date: string;
  end_date: string;
};

export type PayrollContract = StartEndType & {
  type: 'ON_PAYROLL';
  yearly_holidays: number;
};

export type FreelanceContract = StartEndType & {
  type: 'FREELANCE';
  hourly_rate: number;
};

export type Contract = PayrollContract | FreelanceContract;

在我的組件中,它看起來像:

{contractType === 'ON_PAYROLL' ? (
  <Number name="yearly_holidays"  />
) : contractType === 'FREELANCE' && (
  <Number name="hourly_rate" />
)}

當我簽訂 hover 合同時,它知道它是ON_PAYROLLFREELANCE之一。 盡管不幸的是,我的組件中出現了 DeepMap 錯誤。

TypeScript 開箱即用不支持這個嗎?

Property 'yearly_holidays' does not exist on type 'DeepMap<PayrollContract, FieldError> | DeepMap<FreelanceContract, FieldError>'.
  Property 'yearly_holidays' does not exist on type 'DeepMap<FreelanceContract, FieldError>'.

我該如何解決這個問題? 提前致謝。

您能提供Number組件的代碼嗎? 看起來你如何按名稱呈現數字的問題,我能夠在 TS 操場上編譯和使用上面的 TS 代碼。

const renderPayField = (contract: Contract) => {
  if (contract.type === 'ON_PAYROLL') {
     return <Number name="yearly_holidays" />;
  }
  if (contract.type === 'FREELANCE') {
     return <Number name="hourly_rate" />
  }
  return null;
};

此外,更新了一些 TS 以使用接口 + 只讀以提高可讀性

export interface StartEndDate {
  start_date: string;
  end_date: string;
};

export interface PayrollContract extends StartEndDate {
  readonly type: 'ON_PAYROLL';
  yearly_holidays: number;
};

export interface FreelanceContract extends StartEndDate {
  readonly type: 'FREELANCE';
  hourly_rate: number;
};

export type Contract = PayrollContract | FreelanceContract;

暫無
暫無

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

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