Issue
router.get('/cells', async (req, res) => {
try {
const result = await fs.readFile(fullPath, { encoding: 'utf-8' });
res.send(JSON.parse(result));
} catch (err) {
if (err.code === 'ENOENT') { // Object is of type 'unknown'.ts(2571) (local var) err: unknown
await fs.writeFile(fullPath, '[]', 'utf-8');
res.send([]);
} else {
throw err;
}
}
err.code
make this ts error : Object is of type 'unknown'.ts(2571)
I definitely know that err.code
exists, so I want to know how to define the type(or interface) of err
?
(tsc version info : My global typescript version is v4.3.5 and the above code belongs to my project which has typescript v4.1.2)
— Edit —
I finally know why this error happens to me.
I thought I used tsc version under 4.3.x, but it turns out I used v4.4.x.
In vscode, cmd + shift + P
and search for Select Typescript version
and I actually used v4.4.3, (I mistakenly thought on version because I only check tsc version from terminal)
Thanks for sharing Youtube video,
Solution
Just very recently, Typescript has been update to make error object inside catch
be unknown
instead of any
which means, your code looks something like this to your compiler
catch(e: unknown) {
// your logic
}
Provide your own interface and save into another variable to avoid this error:
catch(e : unknown) {
const u = e as YourType
// your logic
}
You can still use any
there, but it’s not recommended.
Answered By – tsamridh86
Answer Checked By – Dawn Plyler (BugsFixing Volunteer)