Home > Enterprise >  Create a sub interface in Typescript
Create a sub interface in Typescript

Time:03-03

I don't know if sub interface is the correct term but, what I want to do is, I want to create an interface that has all the properties of the super interface except some of the optional ones. I've been looking at the Typescript documentation for interfaces but I wasn't able to find what I need.

I know that this is possible by just copy-pasting every prop from the super Interface except the ones that I don't want in the sub interface, however, I don't want this approach because my usecase basically wraps a function that requires an argument of type T, but removes some optional properties before passing them. To put it in a more understandable way, I'll leave a simple example.

interface DefaultParams {
   param1: boolean;
   param2: boolean;
   param3?: boolean;
   ... // and lots of other properties that are coming from the library which I want to include
}

// notice that there is no 'param3' in SubParams interface

interface SubParams {
   param1: boolean;
   param2: boolean;
   ... // and lots of other properties that are coming from the library which I want to include
}

type InnerFunction = (params: DefaultParams) => void;
const funcToCall: InnerFunction = thirdPartyLibrary.function;

function wrapperFunction(params: SubParams) {
   funcToCall(params);
}

Basically what I'm looking for is to create a SubParams interface which will be completely compatible with DefaultParams but it will not include the param3 optional property inside it.

This is my first question on Stackoverflow, I'd appreciate you to correct me if anything is missing or misput.

CodePudding user response:

You can use Omit, for example

interface User {
  name: string;
  age: number;
  gender: "F" | "M";
  phoneNumber: string;
}

interface UserProfile extends Omit<User, "phoneNumber"> {
  address: string;
}

this is means, if a variable set as UserProfile, that variable will have name, age, gender and address without phoneNumber.

Here is for reference https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys

Omit<Type, Keys>

Constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).

  • Related