繁体   English   中英

角2上课

[英]class in class with angular 2

这是我的第一个问题,所以我希望我会适当地提出。 因此,对于我的项目,我需要创建多个组,并在每个组中创建几个人。 现在,我已经创建了一个文件组和一个人文件,它们看起来像这样:

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来测试它,但是我不知道该怎么做。

看起来您在弄混接口

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

您可以这样声明接口:

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怎么办?)
  • 这是一种设计选择,但我会将这些组放在“ Person界面中,而不是像您一样将其放在相反的位置。 这将导致以下接口:
export interface Group {
  id: number;
  name: string;
}

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

接口和类之间有什么区别?

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

课堂 ,另一方面,可以被实例化 这意味着它们可以保存数据(在类实例中)并实现行为(在类方法中)。 即使将TypeScript类仅用于对对象施加形状(如接口那样),它也可以做得更多。 而且,类会保留在最终的JavaScript代码中(在编译之后)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM