最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to initialize a Typescript Interface that has Arrays? - Stack Overflow

programmeradmin0浏览0评论

Let's say I have the following interfaces:

export interface MyObject {
  id: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface MyFile extends MyObject {
  data: any;
  name: string;
}

export interface MyUser extends MyObject {
  name: string;
  photos: Array < MyFile > ;
}

Let's say I have the following interfaces:

export interface MyObject {
  id: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface MyFile extends MyObject {
  data: any;
  name: string;
}

export interface MyUser extends MyObject {
  name: string;
  photos: Array < MyFile > ;
}

How do I initialize a MyUser instance in an, say, Angular app? The issue I'm having is that my object is actually huge, and I thought there would be a way to not having to declare default value for every property, especially that I do have arrays of arrays within my model!

Share Improve this question asked Nov 12, 2017 at 19:15 SammySammy 3,7379 gold badges60 silver badges103 bronze badges 1
  • interfaces don't have initializers. Use classes instead. – Michael Kang Commented Nov 12, 2017 at 19:26
Add a ment  | 

1 Answer 1

Reset to default 4

Anything that conforms to an interface implements it by definition. This is because TypeScript has a structural type system.

Here are a few examples of initializing an implementation of your interface.

const user = {
  id: "1",
  createdAt: new Date(),
  updatedAt: new Date(),
  name: "Kurt",
  photos: [{
    id: "1",
    name: "avatar.png",
    createdAt: new Date(),
    updatedAt: new Date(),
    data: "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="
  }]
};

The object literal above implements the MyUser interface.

You can also specify the interface type on your variable declaration which is helpful in this case since it provides intellisense for the interface members as we are writing the object literal.

const user: MyUser = {
  id: "1",
  createdAt: new Date(),
  updatedAt: new Date(),
  name: "Kurt",
  photos: [{
    id: "1",
    name: "avatar.png",
    createdAt: new Date(),
    updatedAt: new Date(),
    data: "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="
  }]
};
发布评论

评论列表(0)

  1. 暂无评论