简体   繁体   English

typescript中删除function的输入如何声明类型?

[英]How to declare the type for the input of a delete function in typescript?

I'm just starting out learning typescript and I am stuck trying to get types to match.我刚刚开始学习 typescript,我一直在尝试让类型匹配。

I have a delete function that will get rid of a todo item however that function needs to take in an id.我有一个删除 function 将删除待办事项,但是 function 需要输入一个 ID。 In the beginning of my code I defined what a todo looks like which has an optional id property.在我的代码的开头,我定义了一个 todo 的样子,它有一个可选的 id 属性。 It needs to be optional since the formdata that is added when a new todo is created does not have an id property and I can't give one since that is made on the backend.它必须是可选的,因为在创建新待办事项时添加的表单数据没有 id 属性,我不能提供一个,因为它是在后端制作的。 So I am stuck with having optional id properties but id needs to be a number.所以我坚持使用可选的 id 属性,但 id 需要是一个数字。

This is the error:这是错误:

 TS2345: Argument of type '{ id?: number | undefined; name: string; description: string; }' is not assignable to parameter of type '{ id: number; }'. Types of property 'id' are incompatible. Type 'number | undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'. 106 | <h2>{todo.name}</h2> 107 | <p>{todo.description}</p> > 108 | <button onClick={() => deleteTodo(todo)}>Delete Todo</button> | ^^^^ 109 | </div>

Here is my code:这是我的代码:

 interface formState { id?: number name: string description: string } const initialFormState = { name: '', description: '' } as formState interface TodoState { todos: { // The question make means the type for that property is optional. // It can either be a number or undefined id?: number name: string description: string }[] // the brackets above means that its an array } type Itodo = { id?: number name: string description: string } type getTodosQuery = { listTodos: { items: Itodo[] nextToken: string } } function App() { const [todos, setTodos] = useState<TodoState['todos']>([]); const [formData, setFormData] = useState(initialFormState); useEffect(() => { fetchTodos(); }, []); async function fetchTodos() { try { const apiData = (await API.graphql({ query: listTodos })) as { data: getTodosQuery } // console.log("list of todos:", apiData.data.listTodos.items) setTodos(apiData.data.listTodos.items); } catch (error) { console.log(error) } } async function createTodo() { if (.formData.name ||;formData.description) return: await API,graphql({ query: createTodoMutation: variables; { input. formData } }). setTodos([.,;todos; formData ]): setFormData(initialFormState): } async function deleteTodo({ id }. {id. number}) { const newTodosArray = todos;filter(todo => todo;id.== id): setTodos(newTodosArray), await API:graphql({ query: deleteTodoMutation; variables, { input. { id } }}). } return ( <Authenticator> {({ signOut. user }) => ( <div className="App"> <h1>Todo Maker</h1> <input onChange={e => setFormData({,:.formData. 'name'. e.target.value})} placeholder="Todo name" value={formData.name} /> <input onChange={e => setFormData({,:.formData. 'description'. e:target.value})} placeholder="Todo description" value={formData.description} /> <button onClick={createTodo}>Create Todo</button> <div style={{marginBottom. 30}}> { todos.map(todo => ( <div key={todo.id || todo;name}> <h2>{todo;name}</h2> <p>{todo.description}</p> <button onClick={() => deleteTodo(todo)}>Delete Todo</button> </div> )) } </div> <button onClick={signOut}>Sign out</button> </div> )} </Authenticator> ); } export default App;

How can I make todo have an id property be optional but let the delete function take in an id?我怎样才能让 todo 有一个 id 属性是可选的,但让 delete function 接受一个 id?

The simplest way to achieve what you want is to modify the code in the part where you output todos , like this:实现您想要的最简单方法是修改 output todos部分的代码,如下所示:

            {
              todos.map(todo => todo.id && (
                <div key={todo.id}>
                  <h2>{todo.name}</h2>
                  <p>{todo.description}</p>
                  <button onClick={() => deleteTodo(todo)}>Delete Todo</button>
                </div>
              ))
            }

mind the todo.id && part.请注意todo.id &&部分。

Doing so will narrow the type of todo to the type which has id as mandatory field.这样做会将todo的类型缩小为以id作为必填字段的类型。 So then you could use it safely.这样你就可以安全地使用它了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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