spark
spark

Reputation: 1143

how to define function with generic in typescript

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> => {
    
        }
    }

Upvotes: 0

Views: 28

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11340

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>;
    }
}

Upvotes: 1

Related Questions