TS: 6 Techniques For Combining Interfaces and Types

benhultin

ben hultin

Posted on March 27, 2023

TS: 6 Techniques For Combining Interfaces and Types

Typescript offers numerous ways of combing interfaces and types together to create a whole new interface based off of two other ones. That sentenced had two redundant thoughts, should have combined it into a one thought. Maybe this short article will help.

Let's say we have these two interfaces to work with:

interface Parent {
  foo: string;
  bar: string;
  baz: string;
}

interface Uncle {
  foo: string;
  peanuts: string;
  peas: string;
}
Enter fullscreen mode Exit fullscreen mode

We want to combine and re-use them in various ways to create new and interesting interfaces. First something simple.

// Here we extend off of Parent
// Then add carrots property to Sibling
interface Sibling extends Parent {
  carrots: string;
}
Enter fullscreen mode Exit fullscreen mode

In Sibling all Parent properties are required, what if I don't want that?

// we can use Partial<> to define Parent properties as all optional
interface Sibling extends Partial<Parent> {
  carrots: string;
}
Enter fullscreen mode Exit fullscreen mode

What if I only want certain properties from Parent in Sibling?

// will only accept foo and bar from Parent
// foo and bar are required props
interface Sibling extends Pick<Parent, 'foo' | 'bar'> {
  carrots: string;
}
Enter fullscreen mode Exit fullscreen mode

One step further, I want those selected properties from Parent to be optional

// lets combine Partial<> and Pick<> together
// foo and bar are now optional inside of Sibling
interface Sibling extends Partial<Pick<Parent, 'foo' | 'bar'>> {
  carrots: string;
}
Enter fullscreen mode Exit fullscreen mode

Now let's flip all this on its head and do the reverse of Pick<> with Omit<>.

// Omit<> does the oposite of Pick<>
// here we define which props to exclude from the interface/type
// only 'baz' is allowed as a prop
type NewParent = Omit<Parent, 'foo' | 'bar'>;
Enter fullscreen mode Exit fullscreen mode

One more and a little bit different, Extract<> will take the similar properties and a new interface with those

// Extract<> will find the commonalities between types
// Only the props shared between two types will be made into a new type
// only 'foo' is allowed as a prop
type LikeType = Extract<keyof Parent, keyof Uncle>
Enter fullscreen mode Exit fullscreen mode

These are a selection of different built-in tools available in Typescript we can make use of to combine and create new interfaces based off of current ones.

Thanks for reading!

💖 💪 🙅 🚩
benhultin
ben hultin

Posted on March 27, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related