错误:输入 '{ firstName: string;姓氏:字符串;年龄:数字; ...'不能用作索引类型
Err: Type '{ firstName: string; lastName: string; age: number; ...' cannot be used as an index type
我正在尝试将用户列表添加到数组,它抛出上面提到的错误
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"
}
}
];
}
}
谁能解释一下我哪里出错了。
Program Error
代码应该是-
ngOnInit() {
this.users = [
{
firstName: "John",
lastName: "Doe",
age: 30,
address : {
street: "3rd Cross",
city: "Bangalore",
state: "Karnataka"
}
}
];
}
如错误所述,您没有为变量设置值。相反,您试图将值添加为格式错误的数组的索引。
我正在尝试将用户列表添加到数组,它抛出上面提到的错误
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"
}
}
];
}
}
谁能解释一下我哪里出错了。 Program Error
代码应该是-
ngOnInit() {
this.users = [
{
firstName: "John",
lastName: "Doe",
age: 30,
address : {
street: "3rd Cross",
city: "Bangalore",
state: "Karnataka"
}
}
];
}
如错误所述,您没有为变量设置值。相反,您试图将值添加为格式错误的数组的索引。