In my latest project using Next.js, TypeScript, Prisma, and Radix-UI, I'm working with a loan object that has various key-value pairs:
{
"id": 25,
"borrowerName": "Test Borrower 1",
"pipelineStage": "PROSPECT",
"loanAmount": 500000,
"transactionType": "PURCHASE",
"referralSource": "Realtor Lenny",
"borrowerEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd89988e89ccbd9a909c9491d39e9290">[email protected]</a>",
"propertyAddress": "1234 Test Way",
"borrowerPhone": "789-546-3142",
"purchasePrice": 700000,
"creditScore": 700,
"createdAt": "2024-03-15T21:46:18.347Z",
"updatedAt": "2024-03-15T21:46:18.347Z"
}
One of the challenges I encountered was when building a "view single loan" page while trying to convert the createdAt and updatedAt strings from ISO format into a more user-friendly format. Here's a snippet of the code where I loop over the keys and values in one go:
{Object.keys(loan || {}).map((loanKey) => {
if (loanKey === "id") return null;
if (loan && loanKey in loan) {
let value: string | number | Date | null =
loan[loanKey as keyof typeof loan];
if (loanKey === "createdAt" || loanKey === "updatedAt") {
value = new Date(value!).toLocaleString(undefined, {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
});
}
return (
<Card className="text-black">
<Flex direction={"column"} align={"center"}>
<Text>{formatKeyDisplay(loanKey)}: </Text>
<Card>{value}</Card>
</Flex>
</Card>
);
}
return null;
})}
Even though I attempted to cast the value to a Date object and then back to a string for rendering purposes, TypeScript still raised an error stating:
Type 'string | Date | null' is not assignable to type 'ReactNode'.
Type 'Date' is not assignable to type 'ReactNode'.ts(2322)
I also tried typing the value differently with
let value: string | number | null = loan[loanKey as keyof typeof loan];
but it led to another TypeScript error:
Type 'string | number | Date | null' is not assignable to type 'string | number | null'.
Type 'Date' is not assignable to type 'string | number | null'.ts(2322)