Home > front end >  How to destructure a function from props Typescript?
How to destructure a function from props Typescript?

Time:11-02

I have this interface that I want to destructure into props. The problem is, destructuring assignment of function is not working. This function is simply a function that is run at a lower-level component. Do I have a syntax error? Also, why can I not export the const as default?

interface Props {
    day: string;
    options: string[];
    id: string;
    function: () => void;
}

// React FN component
export const group = ({ day, options, id , function } : Props) => {

    // Component logic 
}

CodePudding user response:

function is a reserved keyword. I would try to name is something more descriptive as to what its purpose is. Or, you can use callback if it needs to be generic.

You can have a default const export by doing the following.

const group = ({ day, options, id , callback } : Props)...

export default group;

CodePudding user response:

function is a reserved keyword in javascript & typescript. If you rename the function property to fn or something else then your code no longer gives an error.

interface Props {
  day: string;
  options: string[];
  id: string;
  fn: () => void;
}

// React FN component
export const group = ({ day, options, id , fn} : Props) => {

// Component logic 
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Or you can use

    interface Props {
  day: string;
  options: string[];
  id: string;
  fn: () => void;
}

// React FN component
export const group: React.FC<Props> = ({ day, options, id , fn}) => {

// You can use children, defaultProps 
}

This FC means FunctionalComponent. It provides children, defaultProps fields.

  • Related