0

Lets say I have an interface:

// I get this from an external library so I have no control over it
interface Balloon {
  diameter: number;
  color: "red" | "blue" | "green";
}

And I want to create my own interface that looks like this:

interface Shirt {
  size: "m" | "l" | "xl";
  color: "red" | "blue" | "green";
}

My question is whether it is possible to 'take' the color part from Balloon and inject it into Shirt, so I get something like this:

interface Shirt {
  size: "m" | "l" | "xl";
  color: Balloon.color; // I know this is wrong but it is to illustrate what I want to achieve
}
3
  • 4
    Sure. color: Balloon['color'] Commented Mar 3, 2021 at 10:30
  • @ritaj you can post this as an answer Commented Mar 3, 2021 at 10:39
  • Yes, very simple and elegant solution and very fast response, thank you! Commented Mar 3, 2021 at 10:57

2 Answers 2

0

You could use a base interface:

interface WithColor {
    color: "red" | "blue" | "green";
}

interface Shirt extends WithColor {
  size: "m" | "l" | "xl";
}

Or you could make Color an enum:

enum Color {
    RED = "red",
    BLUE = "blue",
    GREEN = "green",
}

interface Shirt {
  size: "m" | "l" | "xl";
  color: Color;
}

...or even a combination of these two.

while i'd not advise to use types of other interfaces, because that poses a maintainability risk, if you happen to change it on the source interface, this is also a possible way:

interface Shirt {
  size: "m" | "l" | "xl";
  color: "red" | "blue" | "green";
}

interface Balloon {
  size: "m" | "l" | "xl";
  color: Shirt["color"];
}
Sign up to request clarification or add additional context in comments.

2 Comments

The question was about using property type from an existing interface
@ritaj while that is true, that would not be a very good idea to do, as it would reduce maintainability. however, i added the requested solution to the answer.
0
interface Balloon {
    diameter: number;
    color: "red" | "blue" | "green";
}


type Shirt = {
    size: "m" | "l" | "xl";
} & Pick<Balloon, 'color'>

type Check = Shirt['color'] // "red" | "blue" | "green"

Playground

Here you can find more utility types

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.