Home > Software design >  Which type assign to the variable "error"?
Which type assign to the variable "error"?

Time:03-26

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?

CodePudding user response:

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.

  • Related