E0256: catch variable can only be typed as '*', 'any', or 'unknown'
In TypeScript, a catch
variable can be annotated with either no type, *
,
any
, or unknown
. It is an error to annotate a catch
variable with a
specific error type:
function loadConfig(path) {
let json = fs.readFileSync(path, "utf-8");
try {
return JSON.parse(json);
} catch (e: SyntaxError) {
console.warn(`failed to load config: ${e}`);
return null;
}
}
To fix this error, annotate the catch
variable with the unknown
type, then
use instanceof
to check the error's type at run time:
function loadConfig(path) {
let json = fs.readFileSync(path, "utf-8");
try {
return JSON.parse(json);
} catch (e: unknown) {
if (e instanceof SyntaxError) {
console.warn(`failed to load config: ${e}`);
return null;
} else {
throw e;
}
}
}
Introduced in quick-lint-js version 2.7.0.