typescript中的函数覆盖

7lrncoxx  于 2022-12-05  发布在  TypeScript
关注(0)|答案(1)|浏览(172)

我正在尝试在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);
   }
}

我得到一个编译器错误“重复的函数实现”。有什么方法可以创建一个可以接受T或任何的post方法吗?

qyswt5oh

qyswt5oh1#

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

但在您的情况下,还有其他解决方案:

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

当使用泛型时,你总是为它们添加“默认类型”。

相关问题