Issue
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 https://codesandbox.io/s/goofy-spence-ult2wc?file=/src/index.ts
How we can resolve this issue to make sure printForm supports both oldForm and newForm type? Thanks.
Solution
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);
}
};
Answered By - Ehsan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.