Posts > TS Basic: Typing Errors in Try-Catch

TS Basic: Typing Errors in Try-Catch

Sometimes you don’t really know what error your backend or API is providing so Typescript will question the type on your try...catch block your using so this are the different types you can use.

Use any type

using any as type is available as the errors type but this is discourage due to the loss of type safety.

const tryCatch = ( state: 'fail' | 'success' ) => {
	try {
		if ( state === 'fail') {
			throw new Error('Failure!!')
		}
	} catch ( e: any ) {
		return e.message;
	}
}

Coerce as Error

using as keyword is also available but also may loss of type safety and makes a runtime error if your assumption is incorrect

if you have a strong idea of the error’s origin and certain that specific type of error will be thrown you can use the as keyword.

const tryCatch = ( state: 'fail' | 'success' ) => {
	try {
		if ( state === 'fail') {
			throw new Error('Failure!!')
		}
	} catch (e) {
		return (e as Error).message;
	}
}

Check with unknown

it’s better to use the unknown keyword instead of any. As unknown forces type narrowing. Before you can access any properties or call any methods on caught error, you must first check its type.

const tryCatch = ( state: 'fail' | 'success' ) => {
	try {
		if ( state === 'fail') {
			throw new Error('Failure!!')
		}
	} catch ( e ) {
		if (error instanceof Error) {
      // Type narrowing: 'error' is now of type 'Error'
      console.error("An error occurred:", error.message);
      return undefined; // Or handle the error appropriately
    } else if (typeof error === "string") {
      //Type narrowing: error is now of type string.
      console.error("An error string occurred:", error);
      return undefined;
    } else if (typeof error === "number") {
      //Type narrowing: error is now of type number.
      console.error("An error number occurred:", error);
      return undefined;
    } else {
      console.error("An unknown error occurred:", error);
      return undefined;
    } 	
  }
}

Check with instanceof

checks whether an object belongs to a particular class or its subclasses

const tryCatch = ( state: 'fail' | 'success' ) => {
	try {
		if ( state === 'fail') {
			throw new Error('Failure!!')
		}
	} catch (e) {
		if (e instanceof Error) {
			return e.message;
		} else {
			return `Error ${error}`;
		}
	}
}