Home > Mobile >  I have a type defined object and I want to declare a variable and then assign a value to the keys
I have a type defined object and I want to declare a variable and then assign a value to the keys

Time:12-05

I have been working on typescript for the last 4 months only, I am a kinda newbie, and need help. Here is the type definition I am going to use as inferred type.

export type InputFileId = {
  fileId: string;
  rate?: 'satisfied' | 'investigation' | 'wrong' | 'none';
};
export type UserData= {
  uId: string;
};
export type UpdateResponseObject = {
  calculationName?: string;
  temperatureC?: number,
  isLoadChange?: boolean,
  loadN?: number;
  projectId?: string;
  ownersIds?: Array<UserData>;
  fileId?: Array<InputFileId>;
};

Here is what I want to achieve.

const responseData: UpdateResponseObject[] = [];

Now I want to use it as follows

let fileIdArray: any[] = [];

I want to send a response of type UpdateResponseObject and to do so I want to populate the keys/data as defined in the type definition.

responseData.fileId = fileIdArray;

Maybe edit the question or change it or maybe I am stupid.

CodePudding user response:

To use the UpdateResponseObject type and create a new object that conforms to its shape, you can create a new variable and use object shorthand syntax to initialize it with the keys and values you want to include. Here's an example of how you might do that:

const responseData: UpdateResponseObject = {
  fileId: fileIdArray
};

In this example, responseData is declared as being of type UpdateResponseObject, which means that it must have all of the keys defined in that type. Since the fileId property is marked as optional in the type definition, you don't need to include it if you don't want to, but if you do include it, its value must be an array of InputFileId objects.

You could also use the responseData array that you defined earlier, and add objects to it that conform to the UpdateResponseObject type. Here's an example of how you might do that:

const responseData: UpdateResponseObject[] = [];

// Add an object to the array that has a 'fileId' property
responseData.push({ fileId: fileIdArray });

In this example, the responseData array is declared as an array of UpdateResponseObject objects, so each object that you add to the array must conform to the UpdateResponseObject type. You can add as many objects as you want to the array, and each one can have different values for the keys defined in the type.

  • Related