繁体   English   中英

错误 TS2322:“数字”类型不可分配给“字符串”类型

[英]error TS2322: Type 'number' is not assignable to type 'string'

我正在尝试构建一个应用程序,我想首先按用户获取我的帖子,然后在单击帖子时,我想按 id 获取此特定帖子。

最后我收到以下错误:

src/app/cars/car-detail/car-detail.component.ts(25,11) 中的错误:错误 TS2322:类型 'Observable<{ _id: string; 标题:字符串; 内容:字符串; 图像路径:字符串; 创建者:字符串; }>' 不能分配给类型 'Car[]'。

'Observable<{ _id: string; 类型中缺少属性'includes' 标题:字符串; 内容:字符串; 图像路径:字符串; 创建者:字符串; }>'。

src/app/cars/car-detail/car-detail.component.ts(26,11): 错误 TS2322: 类型 'number' 不能分配给类型 'string'。

import { Input, Component, OnInit } from '@angular/core';
import { Car } from '../car.model';
import { CarsService } from '../cars.service';
import { ActivatedRoute, Params } from '@angular/router';


@Component({
  selector: 'app-post-detail',
  templateUrl: './post-detail.component.html',
  styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
  @Input() post: Post[] = [];
  @Input() id: string;
  constructor(
    private postsService: PostsService,
    private route: ActivatedRoute
  ) { }

  ngOnInit() {
    this.route.params
      .subscribe(
        (params: Params) => {
          this.post = this.postsService.getPost(this.id);
          this.id = +params['id'];
        }
      );
  }

}

我该怎么办?

1)

@Input() id: string的类型是string ,但是,当这样做this.id = +params['id']; - +运算符尝试将params['id']解析为number ,所以为什么会出错。

@Input() id: string类型设置为number

2)

this.post = this.postsService.getPost(this.id);

因为我认为getPost返回一个observable 您需要订阅它,然后将调用返回的结果分配给post属性。

this.postsService.getPost(this.id).subscribe(res => this.post = res);

我在尝试这个时遇到了类似的情况。

错误 TS2322:“数字”类型不可分配给“字符串”类型

以下是我在实现节点休息 api 时遇到的错误。

error TS2322: Type 'string' is not assignable to type 'number | FindOperator<number>'.

27     const product = await repository.find({ id: req.params.id });

我必须简单地将变量类型从id:number更改为id: string

此函数中使用的关联变量在另一个文件中声明。 该特定变量的声明类型(在我的例子中它被命名为“id”)与产生错误的行的变量类型不兼容。

所以去声明的地方,根据类型将变量类型设置为数字/字符串,然后它将与其余函数兼容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM