Home > database >  Create type from composed string literal types
Create type from composed string literal types

Time:12-15

I have three Typescript types like this:

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

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

type Child = Mum | Dad;

and I have a function that consumes Child:

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

But I don't want to pass in the entire Child type, only the stage. How can I change this function signature so that it accepts a stage without using any, or keeping a manual copy of the string literal about?

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

CodePudding user response:

You can use an index access type to get the type of stage in Child:

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

Playground Link

CodePudding user response:

You can do two things either directly access stage from Child type or create a Stage type ot of your Child type

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();
  }
}
  • Related