【问题标题】:TypeScript error in angular: A function whose declared type is neither 'void' nor 'any' must return a value角度中的 TypeScript 错误:声明类型既不是“void”也不是“any”的函数必须返回一个值
【发布时间】:2020-12-15 18:59:40
【问题描述】:

我正在尝试突出显示日历上的日期。我将angular-material-datepicker 与dateClass 一起使用。 逻辑很好,但我不知道为什么会出现以下错误。谁能告诉我为什么会出现以下错误?

A function whose declared type is neither 'void' nor 'any' must return a value.

HTML:

<mat-calendar *ngIf="loadCalendar" [dateClass]="dateClass()" [selected]="selectedDate" (selectedChange)="onSelect($event)"></mat-calendar>

Ts:

import { DatePipe } from "@angular/common";
import { Component, OnInit } from "@angular/core";
import { MatCalendarCellCssClasses } from "@angular/material";
import { DataService } from "../app/services/data.service";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
  providers: [DatePipe],
})
export class AppComponent implements OnInit {
  cardData;
  dates: string[] = [];
  loadCalendar: boolean = false;
  constructor(private data: DataService, public datepipe: DatePipe) {}
  ngOnInit() {
    this.data.getData().subscribe((data) => {
      this.cardData = data;
      this.cardData.forEach((element) => {
        //  console.log(this.datepipe.transform(element.start, 'yyyy/MM/dd'));
        this.dates.push(element.start);
        this.loadCalendar = true;
      });
    });
  }

  dateClass() { //Error is caused by this function
      return (date: Date): MatCalendarCellCssClasses => {

        this.dates.forEach((sD)=>{

          let startDate = this.datepipe.transform(sD, "yyyy/MM/dd");
          let calendarDate = this.datepipe.transform( date.getDate(),"yyyy/MM/dd");
          
          if (calendarDate === startDate) {
            return "special-date";
          } else {
            return "";
          }
        })

      };
  }
}

【问题讨论】:

    标签: javascript angular typescript angular-material


    【解决方案1】:
     return (date: Date): MatCalendarCellCssClasses => {  <-- !!!You say it returns a MatCalendarCellCssClasses
    
            this.dates.forEach((sD)=>{
    
              let startDate = this.datepipe.transform(sD, "yyyy/MM/dd");
              let calendarDate = this.datepipe.transform( date.getDate(),"yyyy/MM/dd");
              
              if (calendarDate === startDate) {
                return "special-date";
              } else {
                return""   
              }
            
            })
           return "" <--- you must also return something here incase forEach does not loop 
    }
    

    编辑:随着问题的更新而更新答案

    【讨论】:

    • MatCalendarCellCssClasses 期望返回一个字符串。我试过返回一个空字符串,但发生了同样的错误。
    • 是的,这是有道理的,我完全错过了。谢谢!
    • 如果问题已解决,请将答案标记为已接受。 :)
    猜你喜欢
    • 2018-03-09
    • 2019-01-06
    • 2018-03-18
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2017-06-12
    • 2018-03-15
    • 1970-01-01
    相关资源
    最近更新 更多