Home > database >  Cannot use 'callback' with fs, Typescript
Cannot use 'callback' with fs, Typescript

Time:06-03

Yo, I have this peice of code in my API and it gives me an error I don't understand.

Code :

server.get('/deleteall', async (request, reply) => {
  var json = JSON.stringify(deleteall);
  fs.writeFile('todos.json', json, 'utf8', callback);
  return 'File overwritten.'
})

Error :

Argument of type '(arg0: string, json: string, arg2: string, callback: any) => void' is not assignable to parameter of type 'NoParamCallback'.

The error happens on build, I don't understand it at all, keep in mind, this is my first TS experience.

CodePudding user response:

The callback argument for fs.write() is defined like this:

export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void;

Whatever you have defined as callback does not match that type definition. It should be something like:

function callback(err) {
  console.log(err);
}

Or specified inline:

fs.writeFile('todos.json', json, 'utf8', (err) => console.log(err));

As a more general comment: I suggest you migrate to the promises API to escape callback hell.

  • Related