I’m new in to build a web with React Libray, and use next.js with typscript to create the web app.
And I’m trying to build a todo list web app.
I create an interface for collet the list data like below:
interface listData {
text: string,
isDone: boolean,
viewMode?: { display: '' },
editMode?: { display: 'none' },
}
const [list, setList] = useState<listData[]>([]);
const addList = (item: any) => {
if (item !== "") {
const newList = [...list, { text: item, isDone: false, viewMode: { display: '' }, editMode: { display: 'none' } }];
localStorage.setItem('listData', JSON.stringify([...list, { text: item, isDone: false, viewMode: { display: '' }, editMode: { display: 'none' } }]));
setList(newList);
};
}
The viewMode and editMode is build for display css to show which tag will be show,
like when user press the edit button, then the viewmode.display: ‘none’, otherwise editMode.display: ‘none’.
And now I got a problem about addList assignment problem, please look at the image.
I not sure what the prolem is now in addList function when I setList(newList).
Hope someone can tell me where am I worng, and really thanks for it.
return (
<>
<div className={styles.bodyOuterDiv} >
...
<ul >
{list.map((item, index) => {
return (
<li key={index} className={styles.todoListOuterLi} >
<div className={item.isDone ? styles.todoListItemsWithIsDone : styles.todoListItems} style={item.viewMode}>
{item.text}
</div>
<textarea className={styles.todoListTextArea} value={item.text} onChange={(e) => { setItem(e.target.value) }} style={item.editMode} />
...
</li>
);
})}
</ul>
2
Answers
A fix for the first error with the type:
The problem is that because you don’t have a type annotation on
newList
or the new object in it, TypeScript infers the types of those properties from the types of the property values. When it does that, TypeScript infers""
and"none"
to be of typestring
(rather than the string literal types""
and"none"
), but your interface requires the string literal types""
and"none"
.There are a couple of ways to fix it. Probably the most direct is to tell TypeScript that
newList
is alistData[]
:Playground link
Side note: The
item
parameter’s type should bestring
, notany
.