Typescript抱怨PostResponse []类型上不存在属性名称

在这一行的postData()方法中,

return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res.name);

它抱怨在PostResponse []类型上不存在属性名称。

这是服务中的完整代码,

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ItemsResponse } from './data.interface';
import 'rxjs/add/operator/map';

interface PostResponse {
    data: [
        {
            name: string;
            job: string;
        }
    ];
}
@Injectable()

export class RepositoryService {
    readonly ROOT_URL = 'https://reqres.in/api';
    constructor (private http: HttpClient) {
        console.log('idea repository service instance');
    }
    postData(): Observable<PostResponse> {
        const data = [ {
            name: 'Morpheus',
            job: 'Developer'
        } ];
        return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res[0].name);
   }
}

有人可以告诉我如何正确进行类型转换以及何时使用PostResponse []和PostResponse吗? 错误的屏幕截图

您正在尝试访问数组的name属性。您要么需要访问数组的索引

return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res[0].name);

或更改您期望的类型

 return this.http.post<PostResponse>(`${this.ROOT_URL}/users`, data).map(res => res.name);

编辑-由于您的map方法返回单个字符串,因此您的postData()方法应返回类型Observable<string>

postData(): Observable<string> {
    const data = [{
        name: 'Morpheus',
        job: 'Developer'
    }];
    return this.http.post<PostResponse[]>(`${this.ROOT_URL}/users`, data).map(res => res[0].name);
}

// interface
export interface PostResponse {
    name: string;
    job: string;
}

有关工作示例,请参考AJT_82的stackblitz(stackblitz.com/edit/angular-4mgpbw?file=app%2Fapp.component.‌ts)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TypeScript:类型“ Function”上不存在属性“ propertyName”

Typescript属性“ length”在类型上不存在

TypeScript错误:类型“ Navigator”上不存在属性“ app”

Typescript中的类型“ Date”上不存在属性“ getWeek”

类型'FileList'上不存在TypeScript属性'forEach'

TypeScript中的类型不存在属性

VueJS + Typescript:类型上不存在属性

TypeScript编译错误-类型上不存在属性

TypeScript + Express:类型“ IncomingMessage”上不存在属性“ rawBody”

类型'ChildNode [Typescript]上不存在属性'tagName'

联合体类型上不存在Typescript属性

“类型{}上不存在属性json” TypeScript

TypeScript Joi:类型“ Root”上不存在属性“ validate”

Typescript:组合类型不存在属性?

TypeScript:类型上不存在属性“范围”

属性“名称”在类型“ EventTarget”上不存在-React + TypeScript

TypeScript类型不存在属性“ load”?

类型'ElementFinder'上不存在Typescript属性

Typescript 属性在类型元素上不存在

Typescript 的“对象”错误类型上不存在属性

扩展类型上不存在 Typescript 属性

与 TypeScript 反应 - 类型“EventTarget”上不存在属性“value”

类型上不存在属性:为什么 TypeScript 会抱怨而 JavaScript 不会?

TypeScript - 类型上不存在属性(但它存在)?

TypeScript:类型“any[]”上不存在属性“name”

ReactJS 中的 Typescript 错误 - 类型上不存在属性

TypeScript:禁止联合类型的“类型上不存在属性”

类型“NavigateFunction”Typescript 上不存在属性“push”

与 Typescript 反应:“DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>”类型上不存在属性“名称”