簡體   English   中英

從組合字符串文字類型創建類型

[英]Create type from composed string literal types

我有三個像這樣的 Typescript 類型:

type Mum = {
  stage: "here" | "are" | "some" | "stages";
};

type Dad = {
  stage: "more" | "steps" | "that" | "could" | "happen";
};

type Child = Mum | Dad;

我有一個 function 消耗Child

function myFunc(person: Child): void {
  switch (person.stage) {
    case "here":
    //doThings();
  }
}

但我不想傳遞整個Child類型,只傳遞stage 如何更改此 function 簽名,以便它在不使用any或保留字符串文字的手動副本的情況下接受stage

function myFunc(stage: any): void {
  switch (stage) {
    case "here":
    //doThings();
  }
}

您可以使用索引訪問類型來獲取Child中的stage類型:

function myFunc(stage: Child ['stage']): void {
  switch (stage) {
    case "here":
    //doThings();
  }
}

游樂場鏈接

您可以做兩件事,要么直接從Child類型訪問stage ,要么創建您的Child類型的Stage類型

type Mum = {
  stage: "here" | "are" | "some" | "stages";
};

type Dad = {
  stage: "more" | "steps" | "that" | "could" | "happen";
};

type Child = Mum | Dad;

function myFunc(stage: Child['stage']): void {
  switch (stage) {
    case "here":
    //doThings();
  }
}

type Stages = Child['stage']

function myFunc2(stage: Stages): void {
  switch (stage) {
    case "here":
    //doThings();
  }
}

暫無
暫無

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

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