简体   繁体   English

角2:由其他模型ts组成的模型ts类

[英]Angular 2: model ts class composed of another model ts

I have a Hero and an Address model class, one of the properties of a Hero is its Address which is composed of: street, city.... What's the correct way to specify this in the concrete model source class? 我有一个英雄和一个地址模型类,英雄的属性之一是它的地址,该地址由以下部分组成:街道,城市...。在具体的模型源类中指定此地址的正确方法是什么?

hero.ts: hero.ts:

import {Address} from './address';
export class Hero {
  id: number;
  name: string;
  powers: string [];
  address: Address;
}

address.ts: address.ts:

export class Address {
  street: string;
  street2: string;
  city: string;
  state: string;
}

mock-heroes.ts: 模拟heroes.ts:

import {Hero} from './hero';
export var HEROES: Hero[] = [
  {"id": 11, "name": "Mr. Nice", "powers" : ['nice', 'helpful'], "address" : ("a", "b", "c", "d")},
  {"id": 12, "name": "Narco", "powers" : ['nice', 'helpful'], "address" : ("a", "b", "c", "d")}
];

ERROR when I run "npm start": 运行“ npm start”时出错:

app/mock-heroes.ts(3,12): error TS2322: Type '{ "id": number; app / mock-heroes.ts(3,12):错误TS2322:键入'{“ id”:数字; "name": string; “ name”:字符串; "powers": string[]; “ powers”:字符串[]; "address": string; “地址”:字符串; }[]' is not assignable to type 'Hero[]'. } []'不能分配给'Hero []'类型。 Type '{ "id": number; 输入'{“ id”:数字; "name": string; “ name”:字符串; "powers": string[]; “ powers”:字符串[]; "address": string; “地址”:字符串; }' is not assignable to type 'Hero'. }”不可分配给“英雄”类型。 Types of property 'address' are incompatible. 属性“地址”的类型不兼容。 Type 'string' is not assignable to type 'Address'. 类型“字符串”不可分配给类型“地址”。

它非常简单:

...,'address' : {street:'a', street2:'b', city:'c', state:'d'}, ...

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

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