日本語

How to Fix TS18046 “‘error’ is of type ‘unknown'” in TypeScript catch Blocks

​​TypeScript​Troubleshooting

In TypeScript, reading message from the error variable in catch (error) of a try / catch block gives error TS18046: 'error' is of type 'unknown'. With "strict": true, the type of the variable caught in a catch clause is unknown. If you check with if (error instanceof Error) before reading error.message, the error goes away. This happens when you log or display an error message after a failed JSON load or API call.

I reproduced this error in my test environment, both with tsc and with the TypeScript language server. I confirmed the full message, and that the error disappears after the fix.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and TypeScript 7.0.2. For comparison, I also ran tsc on the same files with TypeScript 5.9.3. The tsconfig.json was created with npx tsc --init and includes "strict": true. I checked the editor errors by running the TypeScript 7 language server (tsc --lsp --stdio) directly, not in the editor itself such as VS Code. I did not test how the errors look in the editor UI.

The full error message

I wrote a function in src/config.ts that loads a config from a JSON string. If JSON.parse fails, it prints the message of the error caught by catch and returns null.

ts
type Config = { port: number };

export function loadConfig(text: string): Config | null {
  try {
    return JSON.parse(text) as Config;
  } catch (error) {
    console.error(`設定を読めませんでした: ${error.message}`);
    return null;
  }
}

Running npx tsc --noEmit produced the following output (exit code 1).

text
src/config.ts(7,35): error TS18046: 'error' is of type 'unknown'.

The message means "error is of type unknown." With --pretty, the location is shown with a squiggly underline (I removed the control characters used for color).

text
src/config.ts:7:35 - error TS18046: 'error' is of type 'unknown'.

7     console.error(`設定を読めませんでした: ${error.message}`);
                                    ~~~~~


Found 1 error in src/config.ts:7

The underline is under the error part of error.message.

The language server reports the same error

With --lsp --stdio, the TypeScript 7 tsc runs as a language server (I started it in the test environment to confirm this). I had this language server open src/config.ts using the same steps an editor takes (initialize, then didOpen). I printed the returned diagnostics and the hover information (type) for error on line 6 with a small script I wrote. The results were as follows.

text
server: typescript-go 7.0.2
diagnostics (1):
  7:35-7:40 severity=1 source=ts code=18046 'error' is of type 'unknown'.
hover 6:12: var error: unknown

severity=1 is the value that the LSP specification uses for errors. The message text is the same as in tsc, and the type of error in catch (error) is unknown.

The catch variable is unknown because of strict

In JavaScript, you can throw any kind of value. You can throw strings and other values, not just Error objects. In the test environment, I ran the following JavaScript with node -e, which throws a string and reads message.

js
try { throw "設定ファイルがありません"; } catch (e) { console.log(e.message); console.log(typeof e); }
text
undefined
string

The value received is a string, so there is no message. In this way, the value received in catch is not always an Error. So with strict enabled, TypeScript types the catch variable as unknown, which represents a value whose contents are not known. You cannot read properties of an unknown value until you narrow its type, for example with instanceof.

According to the TypeScript 4.4 release notes (in English), earlier versions of TypeScript typed catch variables as any. TypeScript 4.4 added the useUnknownInCatchVariables option, and when it is enabled, catch variables are unknown. This option is included in strict, so setting "strict": true turns it on automatically.

In the test environment, running tsc with --useUnknownInCatchVariables false produced no error. When I added this option to tsconfig.json and had the language server open the file, the hover type changed to var error: any.

Checking with instanceof Error removes the error

The fix is to check whether error is an Error object with error instanceof Error before reading message. For values that are not Error objects, the else branch converts the value to a string with String(error) and prints it.

diff
-    console.error(`設定を読めませんでした: ${error.message}`);
+    if (error instanceof Error) {
+      console.error(`設定を読めませんでした: ${error.message}`);
+    } else {
+      console.error(`設定を読めませんでした: ${String(error)}`);
+    }

Inside an if that checks with instanceof, TypeScript narrows the variable's type to that type (see the Handbook's explanation of instanceof narrowing (in English)). After the fix, running npx tsc --noEmit printed nothing and exited with code 0. The language server also reported zero diagnostics. The hover type of error changed depending on the location, as follows.

text
hover 6:12: var error: unknown
hover 8:41: var error: Error
hover 10:46: var error: unknown

The type stays unknown on the catch (error) line (line 6) and in the else branch (line 10). Only inside the if (line 8) does it become Error. (Here I list only the hover lines from the three runs.)

With TypeScript 5.9.3, the same error TS18046: 'error' is of type 'unknown'. appeared at the same location in the original file, and the fixed file had no errors. However, the exit code of tsc when it reports an error was 2 with 5.9.3 and 1 with 7.0.2.

Output when run

I compiled the fixed file to JavaScript with tsc and ran it in Node.js. The calling main.ts is as follows.

ts
import { loadConfig } from "./config.js";

console.log(loadConfig('{"port": 8080}'));
console.log(loadConfig("{"));
text
{ port: 8080 }
設定を読めませんでした: Expected property name or '}' in JSON at position 1 (line 1 column 2)
null

The value thrown by JSON.parse was a SyntaxError, and error instanceof Error was also true (I confirmed this with node -e). Because SyntaxError is a class that inherits from Error, it passes the if branch and message is printed.

I also tested a case where a string is thrown. I ran a file that checks instanceof Error inside catch and outputs String(error) when the value is not an Error.

ts
console.log("メッセージ:", error instanceof Error ? error.message : String(error));
console.log("typeof error:", typeof error);

The output was as follows.

text
メッセージ: 設定ファイルがありません
typeof error: string

Annotating the catch variable's type

You cannot write a type such as Error on a catch variable, as in catch (error: Error). In the test environment, this produced the following error.

text
src/annotate.ts(4,19): error TS1196: Catch clause variable type annotation must be 'any' or 'unknown' if specified.

The message means "If you annotate the catch variable's type, it must be any or unknown."

Writing catch (error: any) removes TS18046. However, any turns off type checking. A file where I mistyped error.message as error.mesage also produced no error from tsc. When useUnknownInCatchVariables is disabled, the variable is also any.

Warning

Writing catch (error: any) or disabling useUnknownInCatchVariables also removes the error, but then the type checker cannot catch the case where message is undefined because a non-Error value was thrown. Use the instanceof Error check before reading message.

Promise .catch gives any

When await is wrapped in try / catch inside an async function, the error in catch (error) is also unknown, and reading message gives the same TS18046.

On the other hand, the argument of the function passed to a Promise's .catch((error) => ...) was any.

ts
Promise.reject(new Error("失敗")).catch((error) => {
  console.error(error.message);
});

This code produced no error from tsc, and the hover type was (parameter) error: any. In the type definitions in lib.es5.d.ts shipped with TypeScript 7.0.2, the argument of .catch is declared as follows.

ts
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;

Because the type definition declares reason as any, TS18046 does not appear inside .catch even with "strict": true. Since no error is reported, you must write your own instanceof Error check to handle a non-Error value when one is passed.

​Posted by 86