OliverRadini
OliverRadini

Reputation: 6467

Exclude the properties of one type from another

If I have three types, say, for instance:

interface TestOne {
  a: number;
  b: string;
}

interface TestTwo {
  c: boolean;
}

interface TestThree {
  a: number;
  b: string;
  c: boolean;
}

How could I define an interface that is the type TestThree without the properties of TestTwo (by that I mean, only a and b).

I appreiate I could use Exclude/Pick and be specific with the keys I want to use/not-use, but in this instance I'd like to be more general about it. Is this possible?

Upvotes: 1

Views: 134

Answers (1)

Mor Shemesh
Mor Shemesh

Reputation: 2889

You can use Omit<T, U> and keyof to achieve that:

interface TestOne {
  a: number;
  b: string;
}

interface TestTwo {
  c: boolean;
}

interface TestThree {
  a: number;
  b: string;
  c: boolean;
}

type TestFour = Omit<TestThree, keyof TestTwo>;

const val: TestFour = {
  a: 0,
  b: ''
}

Typescript Playground

Upvotes: 4

Related Questions