I'm doing a project using TS Vue and I started selecting values from the array returned by the API. It is necessary to compare 2 string values inside the loops, I use === and always get false even with the same values. I tried to make an explicit cast to string, but also did not give any result.
const signers: string[] = (transaction.detailedExecutionInfo as MultiSigExecutionDetails).signers;
console.dir(signers);
console.dir(confirmations[0].signer);
console.log('<--->');
signers.forEach((signer: string) => {
const signerConfirm = confirmations.filter((confirm: MultiSigConfirmations) => {
const address1: string = signer as string;
const address2: string = confirm.signer as string;
console.dir(address1);
console.dir(address2);
console.dir(address1 === address2);
return signer === confirm.signer;
});
console.dir(signerConfirm.length);
});
I even checked directly by comparing two strings with the same values and still get False
console.log(signers[0] === confirmations[0].signer);
How to compare string primitives in TS correctly?
I attach screenshots from the console.
Thank you all in advance for the answers)
CodePudding user response:
The comparison in question is:
console.log(address1 === address2)
However, those appear to be ref
s based on the screenshot of the console.log
.
To correctly compare those ref
s, use the value
property of each ref
:
console.log(address1.value === address2.value)
CodePudding user response:
I tried to make an explicit cast to string, but also did not give any result.
If you're referring to your use of as string
, that does not change the data type to string; it asserts to TypeScript that the value is already a string. However, that's not so: From your screenshot it appears that signer
and confirm.signer
are Objects with a single property, value
; given your use of Vue, they're likely Refs. In Javascript and TypeScript, object equality will be based on identity, not value.
If that's true, you're looking for the comparison address1.value === address2.value
, which will compare strings properly and successfully.