How should I use Try/Catch in TypeScript? I don't want it to check for any errors in a given block because I already check for them (the error is expected and the state is controlled by the catch).
I have the code wrapped in Try/Catch (just example):
try {
let data = localStorage.getItem('something');
// Err. TS2345; I know, that's why you're in the try block
data = JSON.parse(data);
// Err. TS2531; I know, that's why you're in the try block
data.exp = new Date(data.exp * 1000);
return data;
} catch {
return null;
}
TypeScript refuses to compile it. Is there any way I can tell TypeScript that I know about the error and I'm okay with it? I don't want to use //@ts-ignore
on every line (assuming I can have a longer code) and I don't want to turn off strict mode. Is there any better solution?
CodePudding user response:
TypeScript's purpose is to help you with coding errors caused by type issues. It's giving you TS2345 because you're passing string | null
into JSON.parse
(which expects just string
), and it's giving you TS2531 and TS2339 because your code is using data
as though it won't be null
(but it may well be) and as though it has an exp
property (which as far as TypeScript knows, it doesn't).
If you want to disable type checking for data
, use the any
type:
try {
let data: any = localStorage.getItem('something');
// ^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− here
data = JSON.parse(data);
data.exp = new Date(data.exp * 1000);
return data;
} catch {
return null;
}
From the linked documentation:
any
TypeScript also has a special type,
any
, that you can use whenever you don’t want a particular value to cause typechecking errors.