Monday, September 06, 2021

TypeScript 4.4: "catch uknown"

many new linter errors with TypeScript upgrade... 
"solution": catch (err: any)

Announcing T TypeScript 4.4 |ypeScript

In JavaScript, any type of value can be thrown with throw and caught in a catch clause. Because of this, TypeScript historically typed catch clause variables as any, and would not allow any other type annotation:

That’s why TypeScript 4.4 introduces a new flag called --useUnknownInCatchVariables. This flag changes the default type of catch clause variables from any to unknown.

try {
    executeSomeThirdPartyCode();
}
catch (err) { // err: unknown (default type, used to be "any")

    // Error! Property 'message' does not exist on type 'unknown'.
    console.error(err.message);

    // Works! We can narrow 'err' from 'unknown' to 'Error'.
    if (err instanceof Error) {
        console.error(err.message);
    }
}

No comments: