Home > Enterprise >  Typescript try catch function with generics
Typescript try catch function with generics

Time:02-11

I am trying to make one line try catch function which accepts promise and generic type. But when I use my function my generic type doesn't show my generic type

Object is of type 'unknown'.ts(2571)

Instead of showing {type: string}

Here is the function

export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError) {
    return [null, tcError];
  }
};

And here is the usage

const promise = WebBrowser.openAuthSessionAsync();
const [data, error] = await tcatch<{type: string}>(promise);

CodePudding user response:

Typescript has update changed object inside catch to type unknown instead of any so this

export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError) {
    return [null, tcError];
  }
};

actually looks like this:

export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError:unknown) {
    return [null, tcError];
  }
};

that is why you getting object of type unknown to solve this you need to change it to your own interface / type or change it to any.

In your case just add this inside the catch:

  const urType  = tcError as YourInterfaceOrType

OR change to this catch(tcError:any)

CodePudding user response:

I am not sure how correct this solution is but I ended up with this one

export const tcatch = async <DataType, ErrorType>(
  promise: Promise<any>,
): Promise<[DataType | null, ErrorType | null]> => {
  try {
    const tcData = await promise;
    return [tcData as DataType, null];
  } catch (tcError) {
    return [null, tcError as ErrorType];
  }
};

// And then use it next

const [data, error] = await tcatch<{type: string}, {error_type: string}>(authSessionPromise);

const my_data = data?.type;
const my_error = error?.error_type;
  • Related