首页 > 解决方案 > 错误:键入'{ firstName:字符串;姓氏:字符串;年龄:数字;...' 不能用作索引类型

问题描述

我正在尝试将用户列表添加到数组中,它会抛出上述错误

export interface User{
    firstName:string;
    lastName:string;
    age:number;
    address:{
        street:string,
        city:string,
        state:string
    }
}

这是我的界面

在这里我试图添加类型为 user[] 的用户

import { Component, OnInit } from '@angular/core';
import { User } from '../../models/User';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})

export class UsersComponent implements OnInit {

  //Properties
  users :User[];

  //Methods
  constructor() { }

  ngOnInit() {
   this.users[
    {
      firstName: "John",
      lastName: "Doe",
      age: 30,
      address : {
        street: "3rd Cross",
        city: "Bangalore",
        state: "Karnataka"
      }
    }
   ];

  }

}

谁能解释一下我在哪里犯了错误。 程序错误

标签: angularangular5angular6

解决方案


代码应该是 -

ngOnInit() {
   this.users = [
    {
      firstName: "John",
      lastName: "Doe",
      age: 30,
      address : {
        street: "3rd Cross",
        city: "Bangalore",
        state: "Karnataka"
      }
    }
   ];

  }

如错误中所述,您没有将值设置为变量。相反,您试图将值添加为格式错误的数组的索引。


推荐阅读