我试图使用类型记录编写简单的API,它执行code操作,并且在添加任务的代码中出现了下面的错误。我已经创建了包含所有必需属性的接口。下面是代码,您能指点一下吗?因为我觉得这里遗漏了一些东西。我读过下面的文章堆栈溢出,但没有运气。
Error属性'id‘在'Task’类型上不存在
码 ITask.ts
export default interface Task{
id: number,
title: string,
completed: boolean
}
Controller.ts
import Task from '../src/ITask';
import fs from "fs";
import path from "path";
import { ServerResponse, IncomingMessage } from 'http';
const getTask = (req:IncomingMessage, res:ServerResponse) =>{
return fs.readFile(
path.join(__dirname,"store.json"),"utf-8",
(err, data) =>{
if(err){
res.writeHead(500,{"Content-Type" : "application/json"});
res.end(
JSON.stringify({
success: false,
error: err,
}));
} else{
res.writeHead(200,{"Content-Type": "application/json"});
res.end(JSON.stringify({
success: true,
message:JSON.parse(data),
}));
}
}
);
}
const addTask = (req:IncomingMessage, res:ServerResponse) =>{
let data ="";
req.on("data" ,(chunk)=>{
data+= chunk.toString();
});
req.on("end",()=>{
let task = JSON.parse(data);
})
fs.readFile(
path.join(__dirname,"store.json"),"utf-8",
(err,data) =>{
if(err){
res.writeHead(500,{"Content-Type":"application/json"});
res.end(
JSON.stringify({
success: false,
error: err
}
)
);
}else{
// no error, get the current tasks
let tasks : [Task] = JSON.parse(data);
let latest_id = tasks.reduce(
(max = 0, task: Task) => (task.id > max ? task.id : max),
0
);
// increment the id by 1
tasks.id = latest_id + 1;
}
}
)
}
store.json
[
{
"id": 1,
"title": "Learn React",
"completed": false
},
{
"id": 2,
"title": "Learn Redux",
"completed": false
},
{
"id": 3,
"title": "Learn React Router",
"completed": false
},
{
"id": 4,
"title": "Cooking Lunch",
"completed": true
}
]
谢谢
发布于 2022-10-27 08:16:25
任务是一个数组,类型记录在错误消息中用[
]
告诉您这一点。您需要获得其中的一个元素才能获得Task
类型。
https://stackoverflow.com/questions/74225099
复制相似问题