“'对象'类型可分配给很少的其他类型。”

时间:2019-06-30 20:04:32

标签: typescript

在角度8中,我得到:

ERROR in src/app/dashboard/dashboard.component.ts(73,17): error TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
      Type 'Object' is missing the following properties from type '{ x: string; xy: string; xz: string; xc: string; xv: string; xb: string; }': x, xy, xz, xc, and 2 more.

通常,即使对于像我这样的TS新手来说,这也是很容易理解的,但是,在我的代码(在我的Angular组件中)中,我有:

dashContent = {
    x: '',
    xy: '',
    xz: '',
    xc: '',
    xv: '',
    xb: ''
}
dashboard = () => {
    this._dashboardService.dashboard().subscribe((success) => {
            this.dashContent = success;
        }, (error) => {
        }
    )
}

success的返回值是完全相同的对象,但具有填充的属性。

现在,我想实际使用此编码,因为它为对象提供了默认值,但是我如何告诉TS该对象是正确的(我不想在那里打一个any类型) ?

修改

服务:

@Injectable()
export class DashboardService {
  constructor(
    private http: HttpClient,
  ) {
  }

  dashboard() {
    let admin;
    if (localStorage.getItem('role') == 'company') {
      admin = '/company/getDashboard';
    }
    if (localStorage.getItem('role') == 'admin') {
      admin = '/admin/getDashboard';
    }
    return this.http.get(`${environment.origin}${admin}`);
  }
}

1 个答案:

答案 0 :(得分:2)

好吧,首先,TypeScript编译器是正确的,这是一个错误,并且应该是这样。

其次,您可能想知道类型Object事件是从哪里来的,因为您自己没有使用过它。发生的情况是HttpClient.prototype.get被多个签名重载,您的呼叫选择默认签名来返回Observable<Object>。 (这对Angular而言不是一个重大决定)。您可以在angular.io

中找到过载设置

但是,还有另一个重载,采用类型参数,可以在不使用any的情况下解决,而又不损害代码的清晰度。

我建议以下内容:

dash-content.ts

 export default interface DashContent {
    x: string;
    xy: string;
    xz: string;
    xc: string;
    xv: string;
    xb: string;
}

dashboard.service。

import {Injectable} from '@angular/core';

import DashContent from './dash-content';

@Injectable()
export class DashboardService {
  constructor(private http: HttpClient) {}

  dashboard() {
    const role = JSON.parse(localStorage.role);
    const url = `${environment.origin}/${role}/getDashboard`;

    return this.http.get<DashContent>(url);
  }
}

dashboard.component.ts

import DashContent from './dash-content';

export class DashboardComponent {
  dashContent: DashContent = {
    x: '',
    xy: '',
    xz: '',
    xc: '',
    xv: '',
    xb: ''
  }
  dashboard = () => {
    this._dashboardService.dashboard().subscribe(success => {
      this.dashContent = success;
    }, error => {});
  }
}

请注意,HttpClient.Protototype.get调用的原始版本选择了此重载:

get(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<Object>

而修订版选择了此重载:

get<T>(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<T>