typescript type_error ai_generated true

error TS18046: 'x' is of type 'unknown'

ID: typescript/ts18046-unknown-type

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

Catch blocks in TS have unknown error type by default (useUnknownInCatchVariables).

generic

Workarounds

  1. 95% success Narrow the type with instanceof check: if (error instanceof Error) { error.message }
    catch (error) {
      if (error instanceof Error) {
        console.log(error.message);
      }
    }

    Sources: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#instanceof-narrowing

  2. 88% success Use type predicate or assertion function for custom error types
    Use type predicate or assertion function for custom error types

    Sources: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

Dead Ends

Common approaches that don't work:

  1. Set useUnknownInCatchVariables to false in tsconfig 70% fail

    Disables a useful safety feature

  2. Cast error to any 65% fail

    Loses type safety — use proper narrowing instead

Error Chain

Leads to:
Preceded by: