打字稿数组对齐错误

时间:2018-01-05 22:23:14

标签: arrays typescript

我有这堂课:

user.ts

const ADMIN = 1;
const AGENT = 2;
const ADJUSTER = 3;
const MANAGER = 4;
const MOTORCYCLIST = 5;

export class User {
  id: number;
  name: string;
  email: string;
  phone: string;
  status: string;
  role: number;

  isAdmin(): boolean {
    return this.role === ADMIN;
  }

  isAgent(): boolean {
    return this.role === AGENT;
  }

  isAdjuster(): boolean {
    return this.role === ADJUSTER;
  }

  isManager(): boolean {
    return this.role === MANAGER;
  }

  isMotorcyclist(): boolean {
    return this.role === MOTORCYCLIST;
  }
}

出于测试原因,我使用的是模拟用户数组(为简洁起见,我将只显示5个用户的数组,但在我的代码中,我有超过1000个):

模拟users.ts

import { User } from '../models/user';

export const USERS: User[] = [{"id":301,"name":"Shirlee Zboncak","email":"kenyatta_jerde@erdman.ca","phone":"044 93 1342 0977","status":"inactive","role":3},{"id":302,"name":"Erich Auer","email":"grazyna.romaguera@bogisich.name","phone":"044 87 8444 6879","status":"inactive","role":2},{"id":303,"name":"Jerrold McDermott","email":"lindsey_brekke@beierdickinson.info","phone":"044 64 7490 1751","status":"inactive","role":3},{"id":304,"name":"Yael Hilpert","email":"stanton.abbott@pouros.co.uk","phone":"044 16 9190 7970","status":"inactive","role":4},{"id":305,"name":"Pat Hodkiewicz","email":"elin@sanford.biz","phone":"044 12 0242 7692","status":"inactive","role":3}]

问题是该代码失败了this message in console

在我的编辑器中,它显示了另一条消息:

Missing property 'isAdmin' on type '{ "id": number; "name": string; "email": string; "phone": string; "status": string; "role": numbe...'.

如何让我的User类不尝试分配方法。我只想分配那些ID,名称,电子邮件,电话,状态和角色属性。我试图使用构造函数,但错误是相同的。

2 个答案:

答案 0 :(得分:2)

你说你已经尝试过使用构造函数,但也许你没有做到这一点。

这是解决问题的一种方法。首先创建一个接口来统一构造User对象所需的用户数据。

export interface UserData {
  id: number;
  name: string;
  email: string;
  phone: string;
  status: string;
  role: number;
}

然后在User类定义中,声明了UserData类型的字段,其中将保留用户数据。

export class User {
  data: UserData;

  constructor(userData: UserData) {
    this.data = userData;
  }

  isAdmin(): boolean {
    return this.data.role === ADMIN;
  }

  // + all other method declarations
}

如果您不想将用户数据存储到UserData类型的字段中,您可以在构造函数中使用该接口,如下所示:

export class User {
  id: number;
  name: string;
  email: string;
  phone: string;
  status: string;
  role: number;

  constructor(userData: UserData) {
    this.id = userData.id;
    this.name = userData.name;
    // etc.
  }

  isAdmin(): boolean {
    return this.role === ADMIN;
  }
}

然后,您可以使用User关键字和构造函数来实例化new类中的对象,该构造函数将UserData对象作为参数。

export const USERS: User[] = [
  new User({
    id: 301,
    name: "Shirlee Zboncak",
    email: "kenyatta_jerde@erdman.ca",
    phone: "044 93 1342 0977",
    status: "inactive",
    role: 3
  })
];

现在您可以创建User个对象而无需指定方法定义。

答案 1 :(得分:0)

您可以在类中添加构造函数,只需映射数组:

constructor(id,name,email,phone,status,role) {
    this.id = id;
    //...etc
}

然后

export const USERS: User[] = [{...array values}].map(u=>new User(...u))