输入'字符串| null' 不可分配给类型 'string'。类型 'null' 不能分配给类型 'string'

时间:2021-03-15 11:17:51

标签: javascript node.js angular typescript

错误:输入'字符串| null' 不可分配给类型 'string'。类型 'null' 不能分配给类型 'string'。 错误:输入 '{ id?: string |不明确的;标题?:字符串 |不明确的;内容?:字符串 |不明确的; }' 不可分配到类型 'Post'。 属性“id”的类型不兼容。 输入'字符串| undefined' 不能分配给类型 'string'。 类型 '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();

}
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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