【问题标题】:Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'键入'字符串 | null' 不可分配给类型 'string'。类型 'null' 不能分配给类型 'string'
【发布时间】:2021-06-12 15:48:19
【问题描述】:

错误:键入“字符串 | null' 不可分配给类型 'string'。类型“null”不能分配给类型“string”。 错误:键入'{ id?:字符串|不明确的;标题?:字符串 |不明确的;内容?:字符串 |不明确的; }' 不可分配给类型 'Post'。 属性“id”的类型不兼容。 键入'字符串 | undefined' 不能分配给类型 'string'。 类型“未定义”不可分配给类型“字符串”。

export interface Post{
    id:string;
    title:string;
    content:string;
}
import { Component,OnInit} from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Post } from '../post.model';

import { PostsService } from '../posts.service';

@Component({
  selector: 'app-post-create',
  templateUrl: './post-create.component.html',
  styleUrls: ['./post-create.component.css']
})
export class PostCreateComponent implements OnInit {

// newPost='No Content'
enteredTitle='' 
  enteredContent=''
private mode='create'
private postId:string 
private post:Post
  // postId: string | null | undefined;

constructor(public postsService:PostsService
  ,public route: ActivatedRoute){}

ngOnInit(){
  this.route.paramMap.subscribe((paramMap:ParamMap)=>{
    if(paramMap.has('postId')){
      this.mode='edit'
      this.postId=paramMap.get('postId')
      this.post=this.postsService.getPost(this.postId)
    }else{
      this.mode='create'
      this.postId="null";
    }
  });
}

onAddPost(form:NgForm){ 
  if(form.invalid)
  {
    return
  } 
  console.log((form.value.title,form.value.content));
  this.postsService.addPost(form.value.title,form.value.content)

form.resetForm();

}
}

【问题讨论】:

  • 也许可以试试private postId: string = ''
  • 你需要这个吗,this.postId="null"; , 你不能把它改成 ="";
  • @Grumpy this.postId=''null" 可以改为this.postId="" 但问题出在this.postId=paramMap.get('postId') this.post=this.postsService .getPost(this.postId)
  • @Emilien 不,这不是解决方案
  • 使用前需要检查if(postId)

标签: javascript node.js angular typescript


【解决方案1】:

paramMap.get() 返回string|null。由于您的变量严格属于字符串类型,因此 TS 显示错误。
您可以将postId 的类型更改为string|null。
或者做这样的事情this.postId=paramMap.get('postId') || '';

【讨论】:

  • 我在您的解决方案中收到此错误:“字符串”类型不可分配给“字符串”类型。 'string' 是一个原始的,但 'String' 是一个包装对象。尽可能使用“字符串”。
  • 你能检查一下 postId 的类型吗?它可能是“字符串”(包装对象)。它应该是“字符串”(原始)
【解决方案2】:

我认为 paramMap 返回一个布尔值。你需要一个字符串。 “回报 boolean: 如果地图包含给定的参数则为真,否则为假。”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 2021-07-14
    • 2022-01-27
    • 2021-09-06
    • 1970-01-01
    • 2021-09-30
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多