Reputation: 3687
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!
Upvotes: 1
Views: 9010
Reputation: 31823
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="
}]
};
Upvotes: 4