typescript 无法对HttpClient订阅使用sort(),类型“Object”上不存在属性“sort”

1dkrff03  于 2023-11-20  发布在  TypeScript
关注(0)|答案(3)|浏览(192)

我正在从Http迁移到HttpClient,但是我现在遇到了一些错误,因为我不能使用map()对结果进行排序。
使用HttpClient,我得到的属性“sort”在类型“Object”上不存在。

  1. this.getConcept().subscribe(res => {
  2. res.sort((f, n): number => {
  3. if (f.code < n.code) return -1;
  4. if (f.code > n.code) return 1;
  5. return 0;
  6. });
  7. console.error(res);
  8. this.arrConcept = res;
  9. });

字符串
使用Http,我可以毫无问题地排序它。

  1. this.getConcept().map(this.extractData).subscribe(res => {
  2. res.sort((f, n): number => {
  3. if (f.code < n.code) return -1;
  4. if (f.code > n.code) return 1;
  5. return 0;
  6. });
  7. console.error(res);
  8. this.arrConcept = res;
  9. });

jgzswidk

jgzswidk1#

我只需要将res的类型指定为[],就可以让它工作

  1. this.getConcept().subscribe((res:[]) => {
  2. res.sort((f, n): number => {
  3. if (f.code < n.code) return -1;
  4. if (f.code > n.code) return 1;
  5. return 0;
  6. });
  7. console.error(res);
  8. this.arrConcept = res;
  9. });

字符串
然后代码知道res是一个数组,数组有一个sort方法。
如果你已经为数组定义了一个接口,最好使用它。例如:

  1. (res:IConcept[]) => { ... }

展开查看全部
l3zydbqr

l3zydbqr2#

.sort是数组或对象的一个属性,你应该相应地输入你的返回值,然后方法就可以使用了。如果你不确定你的方法的返回值,给予它一个any[]。类似于:

  1. this.getConcept().subscribe((res: any[]) => {
  2. res.sort((f, n): number => {
  3. if (f.code < n.code) return -1;
  4. if (f.code > n.code) return 1;
  5. return 0;
  6. });
  7. console.error(res);
  8. this.arrConcept = res;
  9. });

字符串
但是最好你应该重写你的方法来返回一个合适类型的数组。另外,输入你的函数的返回值。事实上,如果你想使用typescript,输入所有的东西-这就是typescript的作用!=)

ttisahbt

ttisahbt3#

只读

我在尝试.sort()一个只读数组时遇到了这个错误。你可以使用.slice()函数不带参数复制它。在复制的数组上.sort()工作正常。

相关问题