簡體   English   中英

類型 'string' 不可分配給類型 'keyof FitEnum | 不明確的'

[英]Type 'string' is not assignable to type 'keyof FitEnum | undefined'

我正在嘗試編寫用於處理圖像的服務。 我使用 typescript 和夏普。 當我傳遞一個適合的字符串時出現此錯誤。

Overload 2 of 2, '(options: ResizeOptions): Sharp',給出了以下錯誤。 鍵入'字符串 | undefined' 不可分配給類型 'keyof FitEnum | 不明確的'。 類型 'string' 不可分配給類型 'keyof FitEnum | 不明確的'

告訴我如何修復它。

import sharp          from 'sharp';
import FileUpload     from '../FileServices/file_upload';
import {IImageUpload} from './types';

class ImageUpload extends FileUpload implements IImageUpload{

  constructor(
    readonly file: Express.Multer.File,
    readonly width?:number,
    readonly height?:number,
    readonly fit?:string,
    readonly watermark?:boolean,
  ) {
    super(file);
  }

  public async resize_image(){
    let file_info = await sharp(this.bufferFile).resize({
        width: this.width,
        height: this.height,
        fit: this.fit
      }
    ).toBuffer({ resolveWithObject: true })
    this.bufferFile = file_info.data;
  }
}

使用 class ImageUpload

  if(req.file){
    let resizeImg = new ImageUpload(uploadFile,Number(req.body.width),Number(req.body.height),req.body.fit)
    await resizeImg.resize_image();
    let data_file = resizeImg.save_file();
    console.log(data_file);
  }

您聲明readonly fit?: string並將其傳遞給sharp的調整大小配置,該配置需要keyof FitEnum類型而不是字符串。 您可以通過以下方式解決它:

import sharp, {FitEnum} from 'sharp';

...

  constructor(
    ...
    readonly fit?: keyof FitEnum,
    ...
  ) 

與類型定義一樣, fit選項必須是"contain" 、 " cover""fill""inside""outside"之一

   interface FitEnum {
        contain: 'contain';
        cover: 'cover';
        fill: 'fill';
        inside: 'inside';
        outside: 'outside';
    }

   interface ResizeOptions {     
        fit?: keyof FitEnum | undefined;
    }

因此,您需要執行以下操作

import { FitEnum } from 'sharp'

接着

  constructor(
    // other props
    readonly fit?:keyof FitEnum,
  ) {
    super(file);
  }

暫無
暫無

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

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