Home > other >  How can I correctly type a set and implement it?
How can I correctly type a set and implement it?

Time:08-01

I want a typing for an object that replicates a set. For instance, I wish to have the transaction id as a key and the transaction details as the value. In my attempt to do so, I typed it as such,

type TransactionDetail = {
  [key: TransactionId]: TransactionDetails;
};

This will be a prop type for my function,

const handleTransctcionSync = (transaction: TransactionDetail, isChecked: boolean) => {
}

However, I was having a tough time figuring out how to pass the prop to this function. I tried doing this but is not accepted.

handleTransactionDataSync({id: transactionDetails}, !isChecked);      

Any guidance on how to achieve this?

CodePudding user response:

Given the id is const id: TransactionId = transactionDetails.id; then the id should be used as a dynamic object key instead of the literal key "id".

Example:

const id: TransactionId = transactionDetails.id;

...

handleTransactionDataSync({ [id]: transactionDetails }, !isChecked);

or more simply:

handleTransactionDataSync(
  { [transactionDetails.id]: transactionDetails },
  !isChecked,
);

It seems the transaction id is a string type:

type TransactionDetail = {
  [key: string]: TransactionDetails;
};

If transactionDetails is missing properties from TransactionDetails then they either need to be added to transactionDetails or made optional.

interface TransactionDetails {
  // ...the required properties

  // then optional properties
  displayedType?: ....,
  errors?: ....,
  hasNoGains?: ....,
  icon?: ....,
  // ...and 7 more optional
}
  • Related