./resources/typescript-catch-error-types.resources/unknown_filename.png

result.body = error.message

compile error, because the type of the object ’error’ is unknown

result.body = (error as AWSError).message

force casting hides the error, but gives no guarantee that message actually exists! there is no guarantee that error is of type AWSError and actually has that field! And non of the ‘as’ casting remains at runtime So it will just act like message = ‘undefined’ if it is not there

if(error instanceof AWSError) result.body = error.message

compile error, because instanceof AWSError does not work AWSError is NOT an object and does NOT have a constructor

if(error instanceof Error) result.body = error.message

instanceof Error works, because Error is an object with a constructor

if(typeof error === 'AWSError') result.body = error.message

compile error, because typeof only works with “string” | “number” | “bigint” | “boolean” | “symbol” | “undefined” | “object” | “function”

type information is only available at compile time, not at runtime So the type information of AWSError does not exist at runtime in the catch block. Only force casting

ref: Typescript: Type Guards