javascript - 类型 'string | null' 不可分配给类型 'string' 。类型 'null' 不可分配给类型 'string'

标签 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();

}
}

最佳答案

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

关于javascript - 类型 'string | null' 不可分配给类型 'string' 。类型 'null' 不可分配给类型 'string',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66636959/

相关文章:

javascript - 使用 AJAX 在 Node.js 上进行数据库查询

javascript - 类似于 Promise.resolve() 的 Observable 运算符

node.js - Typescript build "Cannot find module",但仅在 ubuntu 服务器上

css - 为 Stylus 设置自动编译

c# - ASP NET Core JWT 身份验证允许过期 token

Angular 4填充下拉列表不起作用

javascript - Javascript 数组中的循环

javascript - 如何解决 Mozilla 中的同源政策

javascript - Nightwatchjs - getElementById 不起作用

在对话框中打开时, Angular 垫 slider 动画从 100 到 0