簡體   English   中英

即使我定義了一個字符串,我也收到了一個錯誤,即使我定義了一個字符串,我也收到了一個錯誤

[英]I'm getting an error even though I defined a string and I'm getting an error even though I defined a string

    import {Pipe, PipeTransform} from '@angular/core';
import {Product} from "./product";

@Pipe({
  name: 'productFilter'
})
export class ProductFilterPipe implements PipeTransform {

  transform(value: Product[], filterText?: string): Product[] {
    filterText = filterText?filterText.toLocaleLowerCase(): null

    return filterText ? value.filter((p: Product) => p.name
      .toLocaleLowerCase().indexOf(filterText) !== -1) : value;
  }

}

TS2322:鍵入“字符串 | null' 不可分配給類型 'string | 不明確的'。
類型 'null' 不能分配給類型 'string | 不明確的'。

TS2345:“字符串”類型的參數 | undefined' 不能分配給'string' 類型的參數。
類型“未定義”不可分配給類型“字符串”。

在此處輸入圖像描述

試試這個

import {Pipe, PipeTransform} from '@angular/core';
import {Product} from "./product";

@Pipe({
  name: 'productFilter'
})
export class ProductFilterPipe implements PipeTransform {

  transform(value: Product[], filterText?: string): Product[] {
    let pattern = filterText ? filterText.toLocaleLowerCase(): null;

    return pattern ? value.filter((p: Product) => p.name.toLocaleLowerCase().indexOf(pattern) !== -1) : value;
  }

}

如果未將 filterText 傳遞給函數,那么您會收到該錯誤,因為您正在嘗試將某些內容分配給未定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM