从组合字符串文字类型创建类型

sen*_*ett 1 typescript

我有如下三种 Typescript 类型:

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

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

type Child = Mum | Dad;
Run Code Online (Sandbox Code Playgroud)

我有一个消耗的函数Child:

function myFunc(person: Child): void {
  switch (person.stage) {
    case "here":
    //doThings();
  }
}
Run Code Online (Sandbox Code Playgroud)

但我不想传递整个Child类型,只想传递stage. 如何更改此函数签名,以便它接受 astage而不使用any,或保留字符串文字的手动副本 about ?

function myFunc(stage: any): void {
  switch (stage) {
    case "here":
    //doThings();
  }
}
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 5

stage您可以使用索引访问类型来获取in的类型Child:

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

游乐场链接