I’m having the default state with useState hook values. And I’m expecting to type the newTask object inside the sendTask function with its keys as an interface.
interface ITask = {
title: string
author: string,
description: string,
status: number,
priority: number
};
const NewTask: FC<Props> = ({ authors, onFinish }) => {
const [title, setTitle] = useState("");
const [author, setAuthor] = useState("");
const [description, setDescription] = useState("");
const [status, setStatus] = useState(false);
const [priority, setPriority] = useState(false);
const sendTask = () => {
let newTask<ITask> = {
title: title,
author_name: author,
description: description,
status: +status,
priority: priority
};
console.log(newTask)
}
}
2
Answers
You can type your state in functional component like below:
There are a few issues with the code you provided.
Firstly, the interface declaration should use = instead of : to assign the interface definition to the variable. So the correct way to declare the ITask interface is:
Secondly, the status and priority state variables are initialized with boolean values, which are not compatible with the number type expected by the ITask interface. You can either change the interface to use boolean types for those properties, or change the initial state values to 0 or 1 for status and 1 or 2 for priority, depending on the possible values that these properties can have.
Assuming that you want to keep status and priority as number types, you can update the state initialization like this:
Finally, when defining the newTask object inside the sendTask function, you should use the : syntax instead of < to assign the ITask type to the newTask variable. So the correct syntax for defining newTask is:
Note that I also changed author_name to author in the object definition, to match the ITask interface.
Putting it all together, the updated code for the NewTask component would look like this: