Reputation: 289
I am new to React and Typescript. I have a page that sends such URL to another one thru GET as below
http://localhost:8080/merchant-partner/0d593974-ff15-4650-a66b-76df7b701faf
As you can see, the URL parameter is based on an UUID String.
I use this UUID parameter to another page
Its code is based on below
export interface IMerchantPartnerProps extends StateProps, DispatchProps, RouteComponentProps<{ merchantId: string }> {}
export const MerchantPartner = (props: IMerchantPartnerProps) => {
useEffect(() => {
props.getEntities(Number(props.match.params.merchantId);
}, []);
I try to convert this UUID String to Typescript Number, but I get a NaN. How can I convert that?
Upvotes: 2
Views: 5536
Reputation: 1074385
I try to convert this UUID String to Typescript Number
You can't reliably convert a UUID to a JavaScript/TypeScript number
. The number
type is a floating-point type and becomes potentially imprecise after the number 9,007,199,254,740,991, which a UUID could easily be much, much larger than.
Instead, ensure that the UUID is formatted in a consistent way (all lowercase or all uppercase, dashes in the canonical places or no dashes at all, etc.), and use string
.
Alternatively, you could convert it to a bigint
if your target environments are very up-to-date (bigint
is a new type in JavaScript in ES2020). You'd convert the individual segments to bigint
according to the standard grouping rules, preface it with 0x
, and pass it in to BigInt()
:
const uuid = "0d593974-ff15-4650-a66b-76df7b701faf";
const bigIntValue = BigInt(
"0x" + uuid.replace(/-/g, "")
);
console.log(bigIntValue.toString());
So it could be a bigint
(in up-to-date modern environments), but not a number
.
Upvotes: 2