TypeScript报错:类型'{ Id: number; Name: string; }'无法用作索引类型,如何解决?
问题解决:TypeScript数组索引类型错误
你遇到的错误原因很明确:数组的索引必须是数字类型,但你在构造函数里写的this.students[{ Id: 0, Name: 'sameh' }];是把一个student对象当作索引来使用,这完全不符合数组的使用规则,所以TypeScript会报错。
要给students数组添加元素,正确的写法有两种:
- 使用数组的
push方法(推荐,自动追加到数组末尾):
import { Component } from '@angular/core'; interface student { Id: number; Name: string; } @Component({ selector: 'sameh-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { students: Array<student> = []; color: string = 'color: red'; color2: string = 'color : blue'; userName: string = ''; title = 'ng-arab'; constructor() { // 用push添加元素到数组 this.students.push({ Id: 0, Name: 'sameh' }); } }
- 指定数字索引赋值(需要确保索引对应位置已存在,或数组长度足够):
constructor() { // 直接给索引0的位置赋值 this.students[0] = { Id: 0, Name: 'sameh' }; }
注意:第二种方式如果数组初始为空([]),直接给索引0赋值会让数组长度变为1,但如果指定的索引大于当前数组长度,中间的位置会填充undefined,所以更推荐用push方法来安全添加元素。
内容的提问来源于stack exchange,提问作者sameh
相关产品推荐
相关产品推荐

