Home > front end >  How to specify an interface with conditional properties in typescript?
How to specify an interface with conditional properties in typescript?

Time:07-02

I'm creating a helper function to create new HTML elements

interface NewElement {
  type: string;
  className: string;
  innerText: string;
  href: string;
}
const createElement = ({ type, className, innerText, href }: NewElement) => {
  const element = document.createElement(type);
  innerText ? (element.innerText = innerText) : null;
  href ? (element.href = href) : null;
  className ? (element.className = className) : null;
  return element;
};

If I want to create a <li> tag I don't need to pass the href for example

const li = createElement({ type: "li", className: "category" });

The warning, rightly states ...Type '{ type: string; className: string; }' is missing the following properties from type 'NewElement': innerText, href

Is there a way to do this?

CodePudding user response:

In Typescript, you can specify a field as optional as below:

interface NewElement {
  type: string;
  className: string;
  innerText?: string;
  href?: string;
}

It's also a good practice to give those optional fields a default value in your function. For example:

const createElement = ({ type, className, innerText = "", href = "" }: NewElement) => {
  // function body
};

Then, you can use the function as in your example:

const li = createElement({ type: "li", className: "category" });
  • Related