簡體   English   中英

typescript 類型/對象的條件屬性

[英]Conditional property for typescript type/object

假設我有一個看起來像這樣的配方成分類型

export type RecipeIngredient = {
  name: string;
  quantity: Number | string;
  measurement: "grams" | "mililitres" | "custom";
};

例子

const potatoes: RecipeIngredient = { name: 'potatoes', quantity: 100, measurement: 'grams' }

這很好,但我也希望在自定義測量時將數量作為字符串。 這可能嗎?

正確的例子

const rosemary: RecipeIngredient = { name: 'rosemary', quantity: 'a handful', measurement: 'custom' }

我想要無效的

const fish: RecipeIngredient = { name: 'fish', quantity: '100g', measurement: 'grams' }
export type RecipeIngredient = {
  name: string;
  quantity: Number;
  measurement: "grams" | "mililitres";
} | {
  name: string;
  quantity: string;
  measurement: "custom";
};

暫無
暫無

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

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