如何解决错误:类型“undefined”不能赋值给类型“File”

huangapple go评论52阅读模式
英文:

How can I solve the error: Type 'undefined' is not assignable to type 'File'

问题

I am trying to make my variable of type File have the parameter undefined but I get the error: Type 'undefined' is not assignable to type 'File'.

我试图让我的类型为 File 的变量具有 undefined 参数,但我得到错误:类型 'undefined' 不能赋值给类型 'File'。

And when I want to use the variable in the method, I get an error saying that it cannot be undefined.

当我想在方法中使用这个变量时,我得到一个错误,说它不能是 undefined。

英文:

I am trying to make my variable of type File have the parameter undefined but I get the error: Type 'undefined' is not assignable to type 'File'.

export class CreateProductoComponent implements OnInit {


  public producto:any = {};


  public file: File = undefined;
  
  
  constructor() { 

  }


  ngOnInit(): void {
    
  }

And when I want to use the variable in the method, I get an error saying that it cannot be undefined.

//Mètode obtenir imatge directe del input
  fileChangeEvent(event:any):void{
    //Validem imatge
    var file;

    if(event.target.files && event.target.files[0]){ //Validem si rebem imatge desde el input
      file = <File>event.target.files[0]; //Guardem l'arxiu en la variable file
      console.log(file);
    }else{  //Si no hi ha imatge
      iziToast.warning({
        title: 'ERROR',
        class: 'text-danger',
        color: 'red',
        position: 'topRight',
        message: 'No hay imágen'
      });
    }

    

    //Validem la mida de la imatge
    if(file.size <= 4000000){
      if(file.type ==){

      }
    }else{
      iziToast.warning({
        title: 'ERROR',
        class: 'text-danger',
        color: 'red',
        position: 'topRight',
        message: 'La imágen supera los 4MB'
      });
    }

  }

答案1

得分: 0

使属性可选,可以加上一个问号,这样它也可以是未定义的。如果不初始化,可以简单地不将 undefined 分配给变量。

链接:https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties

export class CreateProductoComponent implements OnInit {

  public producto: any = {};

  public file?: File;

  constructor() {

  }

  ngOnInit(): void {

  }
}
英文:

Make the attribute optional with a question mark, which lets it be undefined too. You may keep it simpler by not assigning undefined to the variable, if uninitialized it will be undefined already.

https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties

export class CreateProductoComponent implements OnInit {


  public producto:any = {};


  public file?: File;
  
  
  constructor() { 

  }


  ngOnInit(): void {
    
  }

答案2

得分: 0

错误出现在你的 fileChangeEvent 函数中。那里有多个问题,但主要问题是使用 var file 告诉 TypeScript 使用 any 作为 file 的类型。这对于 TypeScript 来说是一个反模式。

具体的错误出现在当你引用 file.size 时,因为 file 可能为 undefined(从技术上讲,file 可能是 任何类型)。

以下内容将解决你面临的与 Type 'undefined' is not assignable to type 'File' 相关的错误:

请注意,重要的更改是首先在你的 if (file) ... 条件中检查 file 是否存在。

// 获取输入中的图像的方法
fileChangeEvent(event: Event): void {
  // 验证图像
  let file: File | undefined;

  if (event.target.files && event.target.files[0]) { // 检查是否从输入接收到图像
    file = <File>event.target.files[0]; // 将文件保存在变量 file 中
    console.log(file);
  } else {  // 如果没有图像
    iziToast.warning({
      title: '错误',
      class: 'text-danger',
      color: 'red',
      position: 'topRight',
      message: '没有图像'
    });
  }

  // 验证图像的大小
  if (file && file.size <= 4000000) {
    // TODO: 完成这段代码
    // if (file.type ==){
    //
    // }
  } else {
    iziToast.warning({
      title: '错误',
      class: 'text-danger',
      color: 'red',
      position: 'topRight',
      message: '图像大小超过4MB'
    });
  }
}
英文:

The error is in your fileChangeEvent function. There are multiple issues there, but the main one is the use of var file tells TypeScript to use any for the type of file. This is an antipattern for TypeScript.

The error specifically occurs when you reference file.size, because it's possible for file to undefined (it's technically possible for file to be any type).

The following will resolve the error you are facing related to Type &#39;undefined&#39; is not assignable to type &#39;File&#39;:

Note that the important change here is to first check if file exists in your if (file) ... condition.

//M&#232;tode obtenir imatge directe del input
  fileChangeEvent(event:Event):void{
    //Validem imatge
    let file : File | undefined;

    if(event.target.files &amp;&amp; event.target.files[0]){ //Validem si rebem imatge desde el input
      file = &lt;File&gt;event.target.files[0]; //Guardem l&#39;arxiu en la variable file
      console.log(file);
    }else{  //Si no hi ha imatge
      iziToast.warning({
        title: &#39;ERROR&#39;,
        class: &#39;text-danger&#39;,
        color: &#39;red&#39;,
        position: &#39;topRight&#39;,
        message: &#39;No hay im&#225;gen&#39;
      });
    }

    

    //Validem la mida de la imatge
    if(file &amp;&amp; file.size &lt;= 4000000){
      // TODO: Complete this code
      // if(file.type ==){
      //
      // }
    }else{
      iziToast.warning({
        title: &#39;ERROR&#39;,
        class: &#39;text-danger&#39;,
        color: &#39;red&#39;,
        position: &#39;topRight&#39;,
        message: &#39;La im&#225;gen supera los 4MB&#39;
      });
    }
  }

huangapple
  • 本文由 发表于 2023年5月18日 04:45:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76276078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定