【问题标题】:Type 'xx' is not assignable to type 'any[] | Iterable<any> | > (Iterable<any> & any[]) | (any[] & Iterable<any>)'类型 'xx' 不可分配给类型 'any[] |可迭代<any> | > (可迭代<any> & any[]) | (any[] & Iterable<any>)'
【发布时间】:2021-05-08 14:24:29
【问题描述】:

我收到以下错误。我一直在尝试解决这个问题一段时间,但没有运气。谁能帮帮我。

类型 'Student' 不能分配给类型 'any[] |可迭代 | (可迭代 & 任何[]) | (任何 [] 和可迭代)'。 “学生”类型是 不可分配给类型“任何 [] 和可迭代”。类型“学生”不是 可分配给类型 'any[]'。

The Code can be found here.

app.component.html

<div *ngFor="let stu of studentSelected; let i = index;">
  <tr>
    <td>{{stu.f}} :</td>
    <ng-container *ngFor="let s of stu.ff">
      <td>{{s.s_name}}</td>
    </ng-container>
  </tr>
</div>

app.component.ts

import { Component, VERSION } from '@angular/core';
import { Student } from './student.model';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  studentSelected: Student | any = {
    f: 'dfd',
    ff: [
      {
        s_name: 'nswq'
      }
    ]
  };
}

School.model.ts

export class School {
  s_name: string;

  constructor(s_name: string = '') {
    this.s_name = s_name;
  }
}

student.model.ts

import { School } from './School.model';

export class Student {
  f: string;
  ff: School[];

  constructor(f: string = '', ff: [] = []) {
    this.f = f;
    this.ff = ff;
  }
}

【问题讨论】:

  • any[] 至少需要一个数组,Student 是一个对象。您需要添加| any
  • @tom10271 但我仍然看不到 html 文件的输出。帮助。
  • 请将相关代码作为代码块放入您的问题中。如果(何时!)链接失效,这个问题将变得毫无用处。
  • @AJT82 我已经添加了相关的代码块。

标签: javascript angular typescript


【解决方案1】:

正如评论中提到的,selectedStudent 是一个对象,因此删除外部 ngFor。此外,从代码中删除所有 any。如果你打算使用any,那么使用 TypeScript 编码是没有用的。因此,删除 any 并将变量声明为 Student 的类型:

studentSelected: Student = {
  f: 'dfd',
  ff: [
    {
      s_name: 'nswq'
    }
  ]
};

我看到您正在使用带有构造函数的类。请注意,您声明 studentSelected 的方式不会是您班级的实例。我喜欢使用接口,除非有特定的原因需要有一个类,比如类特定的方法。你似乎没有,所以我建议你只使用接口:

export interface School {
  s_name: string;
}

export interface Student {
  f: string;
  ff: School[];
}

如果您想将数据作为类,请记住在创建类的实例时,您需要调用new Student({.....})

至于模板...如前所述,从模板中删除外部*ngFor

<tr>
  <td>{{studentSelected.f}} :</td>
  <ng-container *ngFor="let s of studentSelected.ff">
    <td>{{s.s_name}}</td>
  </ng-container>
</tr>

您的StackBlitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2018-04-23
    • 2018-08-30
    • 2017-08-12
    • 2022-08-04
    • 2021-06-10
    • 2019-04-22
    相关资源
    最近更新 更多