[SOLVED] Which type assign to the variable "error"?

Issue

I’ve the following TypeScript code:

import express from "express";

const app = express();
const fs = require('fs')

app.use(express.json())

app.get('/', (req,res) =>{


    fs.readFile("./data/users.json", "utf8", (error: any,data: any) =>{
        if(error){
            console.log(error);
            return;
         }
         console.log(JSON.parse(data));
    })

})

How can I use the error element without specifying the type any? I want the error to be the same as I would have used if I had written this code in NodeJS.. How can I do it? What am I doing wrong?

Solution

The type of readfile is below.

function readFile(path: number | fs.PathLike, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void 

What you can do is

import fs from 'fs';

fs.readFile('',(err: NodeJS.ErrnoException | null) =>{
    err.code
});

When you hover on function your code editor will show the type definition of any function.

Answered By – Rahul Sharma

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *