简体   繁体   中英

How to type async function passed as prop to React component

How should I type an async function that I'm passing to my React component as a property?

My component is defined below. Specifically I don't know how to type the addTask property in my interface:

interface INewTaskEntryProps {
    addTask:any; // this 
}
class NewTaskEntry extends React.Component<INewTaskEntryProps> {
    ...
    render() { 
        return (
            ...
            <button onClick={(e) => this.props.addTask(e)}>Do Something</button>
            ...
        );
    }
}

And my async function is defined like so:

const addTask = async (e) => {
    ...
    try {
        const newID = await mongoTaskCollection.insertOne({
            ...
        });
    }
    ...
}

And finally I pass the async function into my component like so:

<NewTaskEntry addTask={addTask} />

Depending on what addTask returns but can be something like this:

interface INewTaskEntryProps {
  addTask: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void; 
}

In this case you are telling addTask returns void.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM