Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore certain properties in an interface while creating an object in typescript?

Tags:

typescript

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)

like image 441
prasanth Avatar asked Apr 16 '19 11:04

prasanth


People also ask

How do you override properties in interface TypeScript?

Use the Omit utility type to override the type of an interface property, e.g. interface SpecificLocation extends Omit<Location, 'address'> {address: newType} . The Omit utility type constructs a new type by removing the specified keys from the existing type.

How do I make my properties not required in TypeScript?

Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional.

Can you restrict TypeScript object to contain only properties defined by its class?

Typescript can't restrict extra properties Unfortunately this isn't currently possible in Typescript, and somewhat contradicts the shape nature of TS type checking.

How do I make my properties optional in TypeScript interface?

To make a single property in a type optional, create a utility type that takes a type and the property name as parameters and constructs a new type with the specific property marked as optional. Copied!


1 Answers

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" };
like image 64
Z.D. Avatar answered Sep 28 '22 09:09

Z.D.