Reputation: 311
I have interface defined with some properties. I want to create an object from this interface, however while creating I don't want to fully initialize all the properties mentioned in the interface. I just want to initialize few. How can I achieve that? Thank you.
export interface Campaign {
id: string;
name: string;
createdOn: string;
lastUpdated: string;
createdBy: User;
type: CampaignType;
status: CampaignStatus;
startDate: string;
endDate: string;
budget: number;
description: string;
account: Account;
}
i want to create an array of campaign objects. this is what i am trying to do .
let campaigns: Campaign[] = [
{ id:"1",
name: "test campaign"
}
];
however i get the following error .
Type '{ id: string; name: string; }' is missing the following properties from type 'Campaign': createdOn, lastUpdated, createdBy, type, and 6 more.ts(2740)
Upvotes: 9
Views: 9003
Reputation: 1742
You could mark the properties that you don't want to set a value on creation as optional by doing { propName?: propType }
or if want to mark all the properties to be optional, you could use Partial
Partial<{
prop1: string,
prop2: number,
}>
Upvotes: 2
Reputation: 254
you can use Partial -
let campaigns: Partial<Campaign>[] = [
{ id:"1",
name: "test campaign"
}
];
Upvotes: 10
Reputation: 12837
if you make the optional properties nullable it should work.
example:
type User = {
firstName: string;
lastName?: string;
};
// We can assign a string to the "lastName" property
let john: User = { firstName: "John", lastName: "Doe" };
// ... or we can explicitly assign the value undefined
let jane: User = { firstName: "Jane", lastName: undefined };
// ... or we can not define the property at all
let jake: User = { firstName: "Jake" };
Upvotes: 7