最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Type 'undefined' is not assignable to type 'Date' - Stack Overflow

programmeradmin6浏览0评论

actually, I want to show the recorded Date on my page.for that, I have created a function for showing my recorded Date.but I am stuck when I found an unexpected error.

Here is my code:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { BookService } from 'src/app/services/book.service';

@Component({
  selector: 'app-update-book',
  templateUrl: './update-bookponent.html',
  styleUrls: ['./update-bookponent.css']
})
export class UpdateBookComponent implements OnInit {

  updateBookForm:FormGroup
  book:any
  constructor(private service:BookService,private route : ActivatedRoute,private   router:Router,private fb:FormBuilder) { }

  ngOnInit(): void {
    this.service.getBookById(this.route.snapshot.params.id).subscribe(data=>{
      this.book=data;

      this.updateBookForm = this.fb.group({
        id:[data.id],
        title:[data.title, Validators.required],
        author:[data.author, Validators.required],
        description:[data.description, Validatorspose([Validators.required, Validators.minLength(30)])],
        rate:[data.rate],
        dateStart:[this.formatDate (data.dateStart)],
        dateRead:[data.dateRead],
      })
    })
  }

  formatDate(date: Date){
    if(date){
      return new Date(date).toISOString().substring(0,10);
    }
  }

  onSubmit()
  {

  }

}


I am created here"formatDate "function but here is the main problem I am facing.

Here is my Error:-

how i will resolve this issue.please help.

Update

update-bookponent.html


<div class="update-book">

    <form [formGroup]="updateBookForm"(ngSubmit)="onSubmit()">
        
        <div class="form-group">
          <label for="title" class="required">Title</label>
          <input type="text" class="form-control" id="title" formControlName="title" placeholder="Book Title">
        </div>
        <div class="form-group">
            <label for="author" class="required">Author</label>
            <input type="text" class="form-control" id="author" formControlName="author" placeholder="Book Author">
        </div>
        <div class="form-group">
            <label for="description" class="required">Description</label>
            <input type="text" class="form-control" id="description" formControlName="description" placeholder="Book Description">
        </div>
    
        <div class="row">
    
            <div class="col-md-4 col-xs-4 col-sm-4">
                <div class="form-group">
                    <label for="dateStart">Date Start</label>
                    <input type="date" class="form-control" id="dateStart" formControlName="dateStart" placeholder="Date Start">
                </div>
            </div>
            <div class="col-md-4 col-xs-4 col-sm-4">
                <div class="form-group">
                <label for="dateRead">Date Read</label>
                    <input type="date" class="form-control" id="dateRead" formControlName="dateRead" placeholder="Date Read">
                    </div>
            </div>
            <div class="col-md-4 col-xs-4 col-sm-4">
                <div class="form-group">
                    <label for="rate">Rate</label>
                    <input type="number" min="0" max="5" class="form-control" id="rate" formControlName="rate" placeholder="Rate">
                </div>
            </div>
    
        </div>
        <button class="btn btn-success" type="submit">UPDATE</button>
        <button class="btn btn-danger" type="submit" [routerLink]="['/books']" >CANCEL</button>
    </form>
    </div>

book.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/mon/http';
import { Book } from '../interfaces/book'


@Injectable({
  providedIn: 'root'
})
export class BookService {

  readonly baseURL ="http://localhost:59750/api/Books"


  constructor(private http: HttpClient) { }


  getAllBooks()
  {
    return this.http.get<Book[]>(this.baseURL+"/GetBooks");
  }

  addBook(book: Book){
    return this.http.post(this.baseURL+"/AddBook/", book);
  }

  getBookById(id:number)
  {
        return this.http.get<Book>(this.baseURL+"/SingleBook/"+id);
  }

  upDateBook(book:Book){
    return this.http.put(this.baseURL+"/UpdateBook/"+book.id,book);
  }

  

}


Update

book.ts

export  interface Book
{
    id: number;
    title: string;
    description: string;
    author: string;
    rate?: number;
    dateStart?: Date;
    dateRead? : Date;
}

actually, I want to show the recorded Date on my page.for that, I have created a function for showing my recorded Date.but I am stuck when I found an unexpected error.

Here is my code:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { BookService } from 'src/app/services/book.service';

@Component({
  selector: 'app-update-book',
  templateUrl: './update-book.ponent.html',
  styleUrls: ['./update-book.ponent.css']
})
export class UpdateBookComponent implements OnInit {

  updateBookForm:FormGroup
  book:any
  constructor(private service:BookService,private route : ActivatedRoute,private   router:Router,private fb:FormBuilder) { }

  ngOnInit(): void {
    this.service.getBookById(this.route.snapshot.params.id).subscribe(data=>{
      this.book=data;

      this.updateBookForm = this.fb.group({
        id:[data.id],
        title:[data.title, Validators.required],
        author:[data.author, Validators.required],
        description:[data.description, Validators.pose([Validators.required, Validators.minLength(30)])],
        rate:[data.rate],
        dateStart:[this.formatDate (data.dateStart)],
        dateRead:[data.dateRead],
      })
    })
  }

  formatDate(date: Date){
    if(date){
      return new Date(date).toISOString().substring(0,10);
    }
  }

  onSubmit()
  {

  }

}


I am created here"formatDate "function but here is the main problem I am facing.

Here is my Error:-

how i will resolve this issue.please help.

Update

update-book.ponent.html


<div class="update-book">

    <form [formGroup]="updateBookForm"(ngSubmit)="onSubmit()">
        
        <div class="form-group">
          <label for="title" class="required">Title</label>
          <input type="text" class="form-control" id="title" formControlName="title" placeholder="Book Title">
        </div>
        <div class="form-group">
            <label for="author" class="required">Author</label>
            <input type="text" class="form-control" id="author" formControlName="author" placeholder="Book Author">
        </div>
        <div class="form-group">
            <label for="description" class="required">Description</label>
            <input type="text" class="form-control" id="description" formControlName="description" placeholder="Book Description">
        </div>
    
        <div class="row">
    
            <div class="col-md-4 col-xs-4 col-sm-4">
                <div class="form-group">
                    <label for="dateStart">Date Start</label>
                    <input type="date" class="form-control" id="dateStart" formControlName="dateStart" placeholder="Date Start">
                </div>
            </div>
            <div class="col-md-4 col-xs-4 col-sm-4">
                <div class="form-group">
                <label for="dateRead">Date Read</label>
                    <input type="date" class="form-control" id="dateRead" formControlName="dateRead" placeholder="Date Read">
                    </div>
            </div>
            <div class="col-md-4 col-xs-4 col-sm-4">
                <div class="form-group">
                    <label for="rate">Rate</label>
                    <input type="number" min="0" max="5" class="form-control" id="rate" formControlName="rate" placeholder="Rate">
                </div>
            </div>
    
        </div>
        <button class="btn btn-success" type="submit">UPDATE</button>
        <button class="btn btn-danger" type="submit" [routerLink]="['/books']" >CANCEL</button>
    </form>
    </div>

book.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/mon/http';
import { Book } from '../interfaces/book'


@Injectable({
  providedIn: 'root'
})
export class BookService {

  readonly baseURL ="http://localhost:59750/api/Books"


  constructor(private http: HttpClient) { }


  getAllBooks()
  {
    return this.http.get<Book[]>(this.baseURL+"/GetBooks");
  }

  addBook(book: Book){
    return this.http.post(this.baseURL+"/AddBook/", book);
  }

  getBookById(id:number)
  {
        return this.http.get<Book>(this.baseURL+"/SingleBook/"+id);
  }

  upDateBook(book:Book){
    return this.http.put(this.baseURL+"/UpdateBook/"+book.id,book);
  }

  

}


Update

book.ts

export  interface Book
{
    id: number;
    title: string;
    description: string;
    author: string;
    rate?: number;
    dateStart?: Date;
    dateRead? : Date;
}

Share Improve this question edited Apr 6, 2021 at 15:18 asked Apr 6, 2021 at 14:56 user14344635user14344635 16
  • Please also post your HTML code and the JSON data being returned. – user796446 Commented Apr 6, 2021 at 15:01
  • You need to add check for possible undefined value. Add in your formatDate() method the else condition and return a default value if date = undefined. – Dmitry S. Commented Apr 6, 2021 at 15:04
  • I think your book object is not typed and TypeScript cant recognize the dateStart property as Date type. – ShayD Commented Apr 6, 2021 at 15:04
  • 1 Does your Book.dateStart property is of type Date? – ShayD Commented Apr 6, 2021 at 15:15
  • 1 Can you please add the typings of the Book class – Batajus Commented Apr 6, 2021 at 15:16
 |  Show 11 more ments

1 Answer 1

Reset to default 4

So regarding to your question and updates. Your problem is that dateStart is an optional property on you Book class. That's why you got the error message

Argument of type 'Date | undefined' is not assignable to parameter of type 'Date'

because this property can be undefined by design.

To change this you have two options in my opinion.

  1. Make the property dateStart to a "normal" property, so the piler knows that the property is set, by removing the ?.

  2. You can try to cast the property to a Date

    dateStart:[this.formatDate(data.dateStart as Date)],
    

This should also prevent the error message, but you need to take care of a potential undefined value in you formatDate function

发布评论

评论列表(0)

  1. 暂无评论