0

I am defined a function api_post_con like this in typescript:

export const RequestHandler = {
    api_post_con:(url: string,data: any) => {

    }
}

now I want the api_post_con function with generic like this function:

export function api_post<T>(url: string,data: any): Promise<T> {
    return fetch(url,{
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            'x-access-token': 'xxxxx'
        },
        body: JSON.stringify(data),
    })
        .then(response => {
        if (!response.ok) {
            throw new Error(response.statusText)
        }
        return response.json() as Promise<T>
        })
}

how to change the api_post_con function just like api_post function that return generic type? I have tried like this but did not work:

export const RequestHandler = {
        api_post_con<T>:(url: string,data: any):Promise<T> => {
    
        }
    }
1
  • Generic function type parameters always immediately precede the opening parenthesis of the call signature, like this. Does that meet your needs or am I missing something? Commented Feb 10, 2022 at 14:44

1 Answer 1

1

I think what you need is to declare a class, not an object literal:

export class RequestHandler {
    api_post_con<T>(url: string,data: any):Promise<T> {
        return {} as Promise<T>;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.