Home > other >  Function overriding in typescript
Function overriding in typescript

Time:12-02

I am trying to create a method in typescript

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})

export class HttpService {
    private options = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    };

    constructor(private httpClient: HttpClient) {
    }

    public post(url: string, body?: any): Observable<any> {
        let data = (body == null || body == undefined) ? null : JSON.stringify(body);
        return this.httpClient.post(url, data, this.options);
   }

    public post<T>(url: string, body?: any): Observable<T> {
        let data = (body == null || body == undefined) ? null : JSON.stringify(body);
        return this.httpClient.post<T>(url, data, this.options);
   }
}

I am getting a compiler error "Duplicate function implementation" . Is there any way we can create one post method that can accept T or any ?

CodePudding user response:

Function overriding in TypeScript doesn't mean you can have two implementation but that you can have two declarations. So proper would be:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})

export class HttpService {
    private options = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    };

    constructor(private httpClient: HttpClient) {
    }

    public post(url: string, body?: any): Observable<any>
    public post<T>(url: string, body?: any): Observable<T> {
        let data = (body == null || body == undefined) ? null : JSON.stringify(body);
        return this.httpClient.post<T>(url, data, this.options);
   }
}

But in your case there is other solution:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})    
export class HttpService {
    private options = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    };

    constructor(private httpClient: HttpClient) {
    }

    public post<T = any>(url: string, body?: any): Observable<T> {
        let data = (body == null || body == undefined) ? null : JSON.stringify(body);
        return this.httpClient.post<T>(url, data, this.options);
   }
}

When using generics you always add "default type" for them. So you can do post<T = any>

  • Related