Today's challenge is a strange one - I've encountered a bug where the code behaves differently if typeof(transaction)
returns object
instead of the object name. To work around this issue, I introduced a new parameter called transactionType
to my function, but I had to keep the old logic for backward compatibility.
let userId: string;
if (transactionType === TransactionTypes.A) {
userId = (transaction as TransactionA).userid;
} else if (transactionType === TransactionTypes.B) {
userId = (transaction as TransactionB).user.id;
} else if (
transactionType === TransactionC
) {
userId = (transaction as TransactionC).userId;
} else {
console.log("LEGACY TRANSACTION TYPE USED...");
// Legacy code, caused an issue when typeof returns "object"
userId =
(transaction as TransactionA).userid ||
(transaction as TransactionC).userId ||
(transaction as TransactionB).user.id;
}
When typeof
returns object
, the function returns null
for userId
. I want to verify that my new TransactionType
logic is functioning correctly.
To achieve this, I need to create a test case where typeof
returns object
. However, my attempt resulted in a type error from the linter.
Below is the function declaration:
private getTransactionValues(
transaction:
| TransactionA
| TransactionB
| TransactionC,
transactionType?: TransactionTypes,
): TransactionValues {
//...
}
Here's what I tried to make typeof
return object
:
const transaction: TransactionB = (generateRandomTransaction() as Object);
getTransactionValues({
transaction,
//~~~~~~~~~~~~ ^ error linter "object not TransactionA | TransactionB | TransactionC"
transactionType: TransactionType.A,
});
I'm wondering if it's possible to simulate a property with my object so that it will return type object
when passed to the function and checked using typeof
?