具有角度2的类中的类

时间:2017-02-14 10:00:26

标签: arrays class angular

这是我的第一个问题,所以我希望我能正确地提出这个问题。所以,对于我的项目,我需要创建几个组,并在每个组中创建几个人。现在,我创建了一个组文件和一个看起来像这样的文件:

import { Person} from '../person/person';
export class Group {
    id: number;
    name: string;
    I: Person;
}

并且:

export class Person {
    name: string;
    phone:number;
}

现在,当我想为我的组创建一个模拟文件时,我尝试了这个:

import { Group }   from './group';
import { Person}   from '../person/person';

I: Person= {
    name:"test"
    phone: 25
};
export const GROUPS: Group[] = [
  {id: 1, name: "Chefs d'agence", I:Person},
]

(不要注意这个名字,我是法国人)但是它不起作用,所以我尝试了这个:

import { Group }   from './group';
import { Person}   from '../person/person';

export const GROUPS: Group[] = [
  {id: 1, name: "Chefs d'agence", I:Person={name:"test",phone:25},
]

但最后,我在Group上完成了这种类型的错误:

Type '{ id: number; name: string; I: typeof Individu; }[]' is not assignable to type 'Groupe[]'.
Type '{ id: number; name: string; I: typeof Individu; }' is not assignable to type 'Groupe'.
    Types of property 'I' are incompatible.
      Type 'typeof Individu' is not assignable to type 'Individu'.
        Property 'nom' is missing in type 'typeof Individu'.

现在我用一个Person数组测试它,但只测试一个Person但是我不知道怎么做。

1 个答案:

答案 0 :(得分:1)

您似乎混淆了接口

您提供的代码似乎表明您要使用接口。

你可以像这样声明接口:

export interface Person {
  name: string;
  phone: string;
}

export interface Group {
  id: number;
  name: string;
  persons: Person[];
}

然后,使用它们:

const p: Person = { name: 'Pierre', phone: '01.02.03.04.05' };
const g: Group = { id: 340, name: 'Administrateurs', persons: [p] };

附加说明:

  • 电话号码几乎不属于number类型(如果号码从零开始怎么办?如果您需要包含国家/地区代码或分隔符,例如+33?)< / LI>
  • 这是一个设计选择,但我会将这些组放在Person界面而不是像你那样。这将导致以下接口:
export interface Group {
  id: number;
  name: string;
}

export interface Person {
  name: string;
  phone: string;
  groups: Group[];
}

接口和类之间的区别是什么?

接口仅描述数据的形状。您可以使用它们告诉TypeScript编译器(和您的IDE)代码中特定点的数据类型(例如,此方法应返回此类数据,此变量应包含此类对象...)。将TypeScript转换为JavaScript后,接口会从代码中消失。

另一方面,

可以实例化。这意味着它们可以保存数据(在类实例中)并实现行为(在类方法中)。即使使用TypeScript类只是为了将一个形状强加给一个对象(作为一个接口),它也可以做更多的事情。此外,类仍保留在最终的JavaScript代码中(在转换后)。