Home > Software engineering >  How to make sure the function supports two interface type?
How to make sure the function supports two interface type?

Time:08-28

I have a function named printForm, which needs to support two interfaces IOldForm(legacy env) and INewForm(new env) at the same time, but it has the issues below:

interface IOldForm {
  formDescription: string;
  formId: string;
  isOpt: boolean;
  incude?: boolean;
}

interface INewForm extends Pick<IOldForm, "formDescription"> {
  type: string;
  route: string;
}

const oldForm = {
  formDescription: "oldForm",
  formId: "123",
  isOpt: true
};

const newForm = {
  formDescription: "newForm",
  type: "newForm",
  route: "456"
};

const test = (trans: INewForm) => {
  console.log(trans);
};

const printForm = (form: IOldForm | INewForm): void => {
  console.log(form.isOpt);
  test(form);
};

printForm(oldForm);

printForm(newForm);

Here is the codesandbox link enter image description here

How we can resolve this issue to make sure printForm supports both oldForm and newForm type? Thanks.

CodePudding user response:

you must check first that your type is IOldForm or INewForm. like this :

const printForm = (form: IOldForm | INewForm): void => {
// by checking this typescript will be informed that which type you wanna use
if("isOtp" in form){
  console.log(form.isOpt);
  test(form);
  }
};

  • Related