0

Example:

interface IFetcher {
  response: any
  error: any
}

const Fetcher = (url: string): IFetcher => {
  // loads of code here
  return { response, error }
}

Fetcher function returns a response and error, how can i dynamically type my response and error objects, like using some dynamic type arguments?

If i consume my function:

const { response, error } = Fetcher('https://example.com')

I can type it:

const { response, error }: { response: MyCustomInterface, error: MyErrorInterface } = Fetcher('https://example.com')

I need to type response and error differently, depending on the use case. But above example looks kind of ugly. What's the better way to approach this?

UPDATED CODE

interface IFetcher {
  (url: string, method: string, body: unknown, headers?: any): {
    response: unknown;
    error: unknown;
  };
  <T, U>(url: string, method: string, body: unknown, headers?: any): {
    response: T;
    error: U;
  };
}

1 Answer 1

1
interface Fetcher {
    (url: string): {response: unknown, error: unknown}
    <T, U>(url: string): {response: T, error: U}
}
const Fetcher: Fetcher = (url: string) => {
  // loads of code here
    return { response, error } as any;
}

const { response, error } = Fetcher<string[], string>("/api/get-users") // types provided
const test = response; // string[]
const err = error; // string.


const { response: res, error: er } = Fetcher("/api/get-users") // no types provided.
const testType = res; // unknown
const testNext = er; // unknown

let me know if this is what you want.

Sign up to request clarification or add additional context in comments.

3 Comments

What if Fetcher would have more than 1 argument, like: Fetcher = (url: string, method: string)? And <T, U> could be any letter actually? Like <S, G>? Also a bit detailed explanation on interface Fetcher {} would be awesome, for example, why do you use (url: string) twice?
Yeah can have as many arguments as you want, and letters are irrelevant there just placeholders for dynamic types the same way letters are replacement for dynamic numbers in math
I've added updated section to my question, please, take a look at it. It's kind of repetitive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.