Zico Deng
Zico Deng

Reputation: 735

How to reuse subfields in TypeScript

I have interfaces defined below:

interface One {
  one: {
    oneone: string;
    fieldA: string;
    fieldB: string;
    fieldC: string;
  }
}
interface Two {
  two: {
    twotwo: string;
    fieldA: string;
    fieldB: string;
    fieldC: string;
  }
}

As you can see, fieldA, fieldB, and fieldC are sharable. Is there anyway we can share them? Something like

interface SharedFields {
    fieldA: string;
    fieldB: string;
    fieldC: string;
}

interface One {
  one: (extends SharedFields) {
    oneone: string;
  }
}

Upvotes: 1

Views: 32

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152870

You can use an intersection type for this:

interface SharedFields {
    fieldA: string;
    fieldB: string;
    fieldC: string;
}

interface One {
  one: SharedFields & {
    oneone: string;
  }
}

Upvotes: 3

Related Questions